I have a many to many relationship between User and Category through UserCategory as below.
let user = await User.findAll({
where: {
id: req.query.user
},
attributes: ["id", "name"],
include: [
{
model: models.Category,
as: "interests",
attributes: ["id", "name", "nameTH", "icon"],
through: {
model: models.UserCategory,
as: "user_categories",
attributes: ["id", "userId", "categoryId", "updatedAt"]
}
}
],
// Here, I want to order by updatedAt in user_categories
order: [["user_categories", "updatedAt", "DESC"]]
});
How can I order the result by "updatedAt" inside UserCategory model?
Please refer the following code to sort the result by updatedAt
inside UserCategory
model-
let user = await User.findAll({
where: {
id: req.query.user
},
attributes: ["id", "name"],
include: [
{
model: models.Category,
as: "interests",
attributes: ["id", "name", "nameTH", "icon"],
through: {
model: models.UserCategory,
as: "user_categories",
attributes: ["id", "userId", "categoryId", "updatedAt"]
}
}
],
// Here, I want to order by updatedAt in user_categories
order: [[Sequelize.literal('`interests->user_categories`.`updatedAt`'), 'DESC']]
});
I hope it helps!
For those who have error like this: ошибка синтаксиса (примерное положение: \".\")
or
syntax error (approximate position: \ ". \")
First, go to Sequelize.literal()
function
Second, change the argument string from single quotes ('') to double quotes ("")
Then, just swap backticks ( `` ) and double quotes ("")
let user = await User.findAll({
where: {
id: req.query.user
},
attributes: ["id", "name"],
include: [
{
model: models.Category,
as: "interests",
attributes: ["id", "name", "nameTH", "icon"],
through: {
model: models.UserCategory,
as: "user_categories",
attributes: ["id", "userId", "categoryId", "updatedAt"]
}
}
],
// Your changes here
order: [[Sequelize.literal(`"interests->user_categories"."updatedAt"`), 'DESC']]
// order: [[Sequelize.literal('`interests->user_categories`.`updatedAt`'), 'DESC']]
});
Special thanks to @SohamLawar
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