Reputation: 191
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?
Upvotes: 7
Views: 2281
Reputation: 391
For those who have error like this:
ошибка синтаксиса (примерное положение: \".\")
or
syntax error (approximate position: \ ". \")
Go to Sequelize.literal()
function
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
Upvotes: 3
Reputation: 21
This solution is working for me with PostgreSQL. I'm able to add an order clause on the joining table.
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: [[{model: models.Category, as: 'interests'}, {model: models.UserCategory, as: 'user_categories'}, 'updatedAt', 'DESC']]
});
Upvotes: 2
Reputation: 1265
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!
Upvotes: 4