postgresql Node Sequelize 中预先加载模型的排序结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29995116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ordering results of eager-loaded models in Node Sequelize
提问by Wandering Digital
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'.
我有一组复杂的关联模型。这些模型使用连接表关联,每个表都有一个名为“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']
}]
}],
})
回答by Calvintwr
I believe you can do:
我相信你可以做到:
db.Page.findAll({
include: [{
model: db.Gallery
include: [{
model: db.Artwork
}]
}],
order: [
[ db.Gallery, 'order', 'DESC' ],
[ db.Gallery, db.ArtWork, 'order', 'DESC' ]
]
})
回答by Relu Mesaros
If you also use 'as' and let's say you want to order by 'createdDate' , the query looks like this:
如果您还使用 'as' 并且假设您想按 'createdDate' 订购,则查询如下所示:
DbCategoryModel.findAll({
include: [
{
model: DBSubcategory,
as: 'subcategory',
include: [
{
model: DBProduct,
as: 'product',
}
],
}
],
order: [
[
{model: DBSubcategory, as: 'subcategory'},
{model: DBProduct, as: 'product'},
'createdDate',
'DESC'
]
]
})
回答by Shrikant
order: [
[ db.Sequelize.col('order'), 'DESC'], /*If you want to order by page module as well you can add this line*/
[ db.Gallery, db.ArtWork, 'order', 'DESC' ]
]