Reputation: 5970
I am using the following Sequelize request to get a vehicle booking by booking Id. The linked vehicle and its photos are included.
Bookings.findAll({
where: {
id: bookingid,
},
include: [
{
model: db.vehicles,
include: {
model: db.photos,
order: [["photoOrder", "ASC"]],
},
},
],
})
It works in that I get the correct data but the photos are not in order of photoOrder ascending.
[
{
"id": 1,
"bookingCost": 123,
"userId": 1,
"vehicleId": 1,
"vehicle": {
"id": 1,
"model": "fiesta",
"photos": [
{
"id": 2,
"photoOrder": 2,
"photoUrl": "https://xxx.jpg",
"vehicleId": 1
},
{
"id": 1,
"photoOrder": 1,
"photoUrl": "https://yyy.jpg",
"vehicleId": 1
}
]
}
}
]
What am I doing wrong? My associations are:
db.vehicles.hasMany(db.bookings);
db.bookings.belongsTo(db.vehicles);
db.vehicles.hasMany(db.photos);
db.photos.belongsTo(db.vehicles);
Upvotes: 0
Views: 42
Reputation: 9363
order
option is for top level.
You can do
Bookings.findAll({
where: ...,
include: ...,
order: [[db.vehicles, db.photos, "photoOrder", "ASC"]]
})
===============================
UPDATE:
order
option can be applied for include
. However, to take an effect, you'll need to add separate: true
.
Bookings.findAll({
where: ...,
include: {
model: db.vehicles,
include: {
model: db.photos,
separate: true,
order: [["photoOrder", "ASC"]]
}
}
})
This separate: true
will execute 2 queries.
The original answer of putting order
into top-level will execute 1 query.
If data is small, I think either option works just fine, so it's just a preference.
Upvotes: 1