I have a complex set of associated models. The models are associated using join tables, each with an attribute called 'order'. I need to be able to query the parent model 'Page' and include the associated models, and sort those associations by the field 'order'.
The following is having no effect on the results' sort order:
db.Page.findAll({ include: [{ model: db.Gallery, order: ['order', 'DESC'], include: [{ model: db.Artwork, order: ['order', 'DESC'] }] }], })
Sequelize eager loading is a way to fetch data from multiple tables that have relations between each other. When you use the eager loading technique, the generated SQL query will have one or more JOIN clauses. Let’s see an example of Sequelize eager loading in action. Suppose you have two tables in your database named Users and Invoices as follows:
Sign in to your account When eager-loading nested includes in findAll (), it is not possible to order by attributes of the nested associations.
To keep order in Sequelize we use order param. It gets an array of order specifications. These order specifications are also arrays, but defined in particular way. The simplest variant is just:
Can also be a sequelize model if you want to define the junction table yourself and add extra attributes to it. The model used to join both sides of the N:M association. A key/value set that will be used for association create and find defaults on the through model.
I believe you can do:
db.Page.findAll({ include: [{ model: db.Gallery include: [{ model: db.Artwork }] }], order: [ // sort by the 'order' column in Gallery model, in descending order. [ db.Gallery, 'order', 'DESC' ], // then sort by the 'order' column in the nested Artwork model in a descending order. // you need to specify the nested model's parent first. // in this case, the parent model is Gallery, and the nested model is Artwork [ db.Gallery, db.ArtWork, 'order', 'DESC' ] ] })
There are also a bunch of different ways, or things you can do when ordering. Read more here: https://sequelize.org/master/manual/model-querying-basics.html#ordering-and-grouping
If you also use 'as' and let's say you want to order by 'createdDate' , the query looks like this:
DbCategoryModel.findAll({ include: [ { model: DBSubcategory, as: 'subcategory', include: [ { model: DBProduct, as: 'product', } ], } ], order: [ [ {model: DBSubcategory, as: 'subcategory'}, {model: DBProduct, as: 'product'}, 'createdDate', '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