I have 3 tables such as user
, userProfile
and userProfileImages
. User
is mapping with userPrfoile
as has many and userProfile
is mapping with userProfileImages
as has many.
I need to write the order by query in userProfileImages
, I tried as below, but no luck.
User.findById(uID, {
include: [
model: sequelize.models.userProfile
as: userProfile,
include: [
{
model: sequelize.models.userProfileImages,
as: 'profileImages',
}
],
order: [[sequelize.models.userProfileImages.id, "desc"]]
// order: [["id", "desc"]] --> Tried this way also no luck
] }
I am getting the result, but userProfilePicture
table's result is not as desc.
Kindly give the solutions
Order by included modelfindAll({ order: [[Survey_Questions, "orderIndex", "ASC"]], include: { model: Survey_Questions, }, }); We added model to include and the same model is used in order params, where we declare that we want to order results by orderIndex from joined table.
There are two ways you can create JOIN queries and fetch data from multiple tables with Sequelize: Create raw SQL query using sequelize. query() method. Associate related Sequelize models and add the include option in your Sequelize query method.
findByPk The findByPk method obtains only a single entry from the table, using the provided primary key. const project = await Project. findByPk(123); if (project === null) {
How do you include two models in Sequelize? 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.
From Sequelize offical docs:
// Will order by an associated model's created_at using an association object. (preferred method)
[Subtask.associations.Task, 'createdAt', 'DESC'],
// Will order by a nested associated model's created_at using association objects. (preferred method)
[Subtask.associations.Task, Task.associations.Project, 'createdAt', 'DESC'],
By referring above syntax, Update your order option like below
User.findById(uID, {
include: [{
model: sequelize.models.userProfile
as: userProfile,
include: [{
model: sequelize.models.userProfileImages,
as: 'profileImages',
}],
order: [['profileImages','id', 'desc']]
}]
});
Official Documentations: http://docs.sequelizejs.com/manual/tutorial/querying.html#ordering
Refer this thread for more solutions: https://github.com/sequelize/sequelize/issues/4553
Update your order in association like below
User.findById(uID, {
include: [
model: sequelize.models.userProfile,
as: userProfile,
include: [{
model: sequelize.models.userProfileImages,
as: 'profileImages',
separate:true
order: [['id', 'desc']]
}],
]});
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