Sequelize - SQL Server - order by for association tables

拜拜、爱过 提交于 2019-12-30 10:37:21

问题


I have 3 tables such as user, userProfile and userProfileImages. User is mapping with userPrfoile as has many and userProfile is mapping with userProfileImages as has many.

I need to write the order by query in userProfileImages, I tried as below, but no luck.

User.findById(uID, { 
include: [
   model: sequelize.models.userProfile
   as: userProfile,
   include: [
    {
      model: sequelize.models.userProfileImages,
      as: 'profileImages',

    }
   ],
    order: [[sequelize.models.userProfileImages.id, "desc"]]
  // order: [["id", "desc"]] --> Tried this way also no luck
] }

I am getting the result, but userProfilePicture table's result is not as desc.

Kindly give the solutions


回答1:


From Sequelize offical docs:

    // Will order by an associated model's created_at using an association object. (preferred method)
    [Subtask.associations.Task, 'createdAt', 'DESC'],

    // Will order by a nested associated model's created_at using association objects. (preferred method)
    [Subtask.associations.Task, Task.associations.Project, 'createdAt', 'DESC'],

By referring above syntax, Update your order option like below

User.findById(uID, { 
    include: [
        model: sequelize.models.userProfile
        as: userProfile,
        include: [{
           model: sequelize.models.userProfileImages,
           as: 'profileImages',
        }],
        order: [['profileImages','id', 'desc']]
    ]
});

Offical doc: http://docs.sequelizejs.com/manual/tutorial/querying.html#ordering

Refer this thread for more solutions: https://github.com/sequelize/sequelize/issues/4553



来源:https://stackoverflow.com/questions/46027310/sequelize-sql-server-order-by-for-association-tables

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