How can i translate query to sequelize? - javascript

select reservation_datetime
from LectureReservation
Inner Join Lecture
On LectureReservation.lecture_id = Lecture.id
Where Lecture.mentor_id = 1
This is my query and I want to change it to sequelize like
if (req.params.id) {
LectureReservation
.findAll({
include: [{
model: Lecture,
where: { mentor_id: req.params.id },
}],
attributes: ['reservation_datetime'],
where: {
lecture_id: Lecture.id,
},
this.. I tried it so hard but can't find solution and my postman keep showing me
"name": "SequelizeEagerLoadingError"
this err..
plz help me to translate query to sequelize..!

Sequelize will do _outer join without required = true.
The errors you have received usually is from association problem.
Try set logging :console.log and check the raw query.

Related

Sequelize: use field created in sequelize.literal in where clause

I am using sequelize .literal function to create an aggragated field, which was not achievable in other ways. Now I want to use sequelize's built-in "where" clause to filter by values on this new field.
DB_A.findAll({
attributes: {
include: [
[
sequelize.literal(
`(SELECT COUNT (*) FROM DB_B as DB_B WHERE DB_B.a_id = DB_A.id)`
),
"b_count",
],
]}
where:{ b_count:{[Op.gte]:10}}
})
When I do this, I get "Unknown column 'DB_A.b_count' in 'where clause'". I've also tried:
where:{[sequelize.literal("b_count")]:...}
Which works with the order property from sequelize, but not here.
Any ideas?
Ok, I figured it out. You need to use "having" instead of "where", as it would be the way to do with regular MySQL. For some reason Sequelize.having is not on the DOCS/API, and I already opened an issue at the git repo.
The above code would then be:
DB_A.findAll({
attributes: {
include: [
[
sequelize.literal(
`(SELECT COUNT (*) FROM DB_B as DB_B WHERE DB_B.a_id = DB_A.id)`
),
"b_count",
],
]}
having:{ ["b_count"]:{[Op.gte]:10}}
})

Where with OneToMany relation in TypeORM

How to create a function in TypeORM to find an data by time range in OneToMany entity?
I create an where clause to find:
const users = await this.conn
.getRepository(User)
.find({
select: ['id', 'firstName', 'lastName', 'sex', 'birthdate', 'subAddress', 'address', 'city', 'district', 'disabilityType'],
join: {
alias: "user",
leftJoinAndSelect: {
order: "user.orders"
}
},
where: {
order.createdAt: Between(dto.from, dto.to)//HERE
}
});
but it not work and always throw me NOT_FOUND :/
can someone show how this should be?
You are trying to get the results based on filter for the child record and I am not sure if it works with typeorm(based on my experience with other language).
However I found some articles on GitHub which may help you.
An alternative solution link:
here
Bug reported and in status open:here
I hope it guides you somehow

Making a JOIN WHERE key IN(SELECT key FROM...) using Sequelize.js

Im a noob in Sequelize.js and somewhat less in Angular but must solve a problem in which I want to use a subquery as a condition of a JOIN. I paste some examples below because code says more then words.
SQL
INNER JOIN table ON table.key IN(SELECT current_key FROM historysnake WHERE original_key IN(
SELECT original_key FROM historysnake WHERE current_key = table.key)
AND historysnake.model = 'tablename')
The question is: How can I put above query into a Sequelize object? Something like:
Sequelize.js
var foo = sequelize.define('foo', {...}, {
classMethods: {
associate: function(models) {
foo.hasMany(...)
}
}
});
Ok, here's an example, which assumes that PK of PatientEvents is the original_key on all the history rows:
PatientEvents.hasMany(HistorySnake, {foreignKey : 'original_key'});
PatientEvents.findAll({
include: [{
model: HistorySnake,
required : true, // true = INNER JOIN but you might need outer join to see events with no history
where : { modelName : 'PatientEvents' } // as needed
}],
where: { patient_name : 'xyz' } // as needed
})
I figured it out. I'm not really sure if #KenOn10's answer would've worked. I'm too much of a noob on this subject for that but thanks for the answer anyway.
I ended up specifying my own 'on' clause like this.
models.Aim.find({
include: [{
model: models.ObjectiveReport,
required: false,
where: ['ObjectiveReports.report_entrydate >= ?', show_date],
on: {
aim_id: sequelize.literal('aim.aim_id IN(SELECT current_key FROM historysnake WHERE original_key IN(SELECT original_key FROM historysnake WHERE current_key = aim.aim_id) AND historysnake.model = "aim")')
})
...

Sequelize order by id for root table when we are using join method

this below Sequelize work fine for me without using order, i'm wondering why i can't use order for root table as posts model? when i use this below code i get this error:
Unhandled rejection Error: 'posts' in order / group clause is not valid association
but that work fine on other models such as channelVideoContainer
models.posts.findAll({
where: {
channelId: 1
},
include: [
{
model: models.channelVideoContainer,
include: [models.fileServerSetting]
}, {
model: models.channelMusicContainer,
include: [models.fileServerSetting]
}, {
model: models.channelImageWithTextContainer,
include: [models.fileServerSetting]
}, {
model: models.channelFilesContainer,
include: [models.fileServerSetting]
},
models.channelPlainTextContainer
], order: [
[{model: models.posts}, 'id', 'DESC'],
], limit: 5
}).then(function (result) {
console.log(JSON.stringify(result));
});
You are getting this error because you are querying the posts table/model, and then sorting by a column on the posts model, however you are specifying a "joined" table in your order. This works for your other models because they are in fact joined (using the include option). Since you are querying the posts model you just need to pass in the name of the column you want to order by. See some of the ORDER examples in the documentation.
// just specify the 'id' column, 'post' is assumed because it is the queried Model
order: [['id', 'DESC']],
As a side note, you may want to specify required: false on your include'd models to perform a LEFT JOIN so that rows come back even if there are no matches in the joined table. If you know that rows will be returned (or they are actually required) then leave it as is.
{
model: models.channelFilesContainer,
include: [models.fileServerSetting],
required: false, // LEFT JOIN the channelFilesContainer model
},

How bind search values in mongodb with mongoose

I have the following code in my /search/:query route:
var param = {
query: req.query['query']
}
MyModel.find({
"$or": [
{ 'name': req.param.query },
{ 'age': req.param.query },
{ 'event': req.param.query },
]
}, function (err, results) {
if (err) {
console.log(err)
}
else {
res.render('index', {
data: results
});
}
}
);
And is good, i can search for pretty much every data that i want, but only individually. What if i want search name + age, can i? Example: 'Leo 22'.
There is any way that mongoose help me with this?
UPDATE:
My problem is:
I have tables lists it titles, this title is the concatenation of 'eventName' and 'eventDate'.
Real examples of this fields:
'Special Event - 20/12/2015'
'Classic Event - 12/03/2015'
'Hot Summer Event - 05/07/2005'
Every week will be create 4 events. In some point, a user will search for an old event, and i believe that the user will search in this format:'EVENT NAME - EVENT DATE'..
So i need a way to bind this values in my controllers.
I'm no familiar with mongoose but in order to do that, you must have a way to bind your query param to the attribute you want to search. Otherwise, they wouldn't know Leo is name and 22 is age.
Ur path would be like search?name=:name&age=:age&event=:event and in your code, you will have to process like if the param is not null, add and condition to it.
It seems you are using only one parameter (req.param.query) to filter all attributes. That's not mongoose related: you could create distinct parameters for each attribute and pass them along the query string.
For instance:
"$or": [
{ 'name': req.param.name },
{ 'age': req.param.age },
{ 'event': req.param.event },
]
And your HTTP request will be like this:
http://youraddress/expressRoute?name=Leo&age=22

Categories

Resources