I have a model with 3 entities, Documents, Employees and Managers. A Document belongs to and Employee and an Employee belongs to a Manager. My objective is to retrieve all the documents of a manager employees.
My piece of code is working
Document.findAll({
include: [{
model: models.Employee,
required: true,
as: 'employee',
include: [{
model: models.Manager,
required: true,
as: 'manager',
}],
}],
But I'm not really satisfied, I would like to have my where condition outside my include but when I try
where {
'employee.manager.id': id
}
an error is raised.
Is it possible to setup a where condition outside the includes ?
EDIT :
I changed my code to
Document.findAll({
where: {'$employee.manager.id$': id},
include: [{
model: models.Employee,
required: true,
as: 'employee',
include: [{
model: models.Manager,
required: true,
as: 'manager',
where: { id: managerId },
}],
}],
and it's working.
Now, I would like to refine my model. Each document as a type (administrative, evaluation ...) and I would like to retrieve the most recent document for each type for each manager. I used an order by which is working fine and tried to use a group by which is not working
order: [ [ 'updatedAt', 'DESC' ]],
group: ['type'],
I get the following message : column \"Document.id\" must appear in the GROUP BY clause or be used in an aggregate function.
Any idea what I'm doing wrong ?
To wrap up, include takes an array of objects. These objects are queries of their own, essentially just Sequelize queries within our main query. Inside each include query we specify the associated model , narrow our results with where , and alias our returned rows with as .
Your solution, along with using include: {all:true} in my findAll query, did the trick. instead of using include: {all:true} in findAll you can use include: {model: models. User, as: 'createdByUser'} , etc. Be sure to use as: in all associations to the same model in your Sequelize model declaration.
To change the JOIN clause from LEFT OUTER JOIN to INNER JOIN , you need to add the required: true option to the include option. Here's how you call the findAll() method to produce an INNER JOIN query: const users = await User. findAll({ include: { model: Invoice, required: true }, }); console.
Yes, you can do that ,
Issue with current one :
where {
'employee.manager.id': id // <--- Here 'employee.manager.id' cosidered as whole column name
}
Solution :
where {
'$employee.manager.id$': id //<--- To make sequlize realize you need to place it b/w $$ ,
//or
sequelize.col('employee.manager.id') : id // <--- You can try this also
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With