Ordering results of eager-loaded models in Node Sequelize

爷,独闯天下 提交于 2020-05-09 18:07:16

问题


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']
    }]
  }],
})

回答1:


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' ]
  ]
})



回答2:


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'
        ]
    ]
})



回答3:


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' ]
]


来源:https://stackoverflow.com/questions/29995116/ordering-results-of-eager-loaded-models-in-node-sequelize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!