Sequelize - SQL Server - 按关联表排序

时间:2017-09-03 19:53:00

标签: node.js express sequelize.js

我有3个表格,例如useruserProfileuserProfileImagesUseruserPrfoile的映射一样多,userProfileuserProfileImages的映射一样多。

我需要在userProfileImages中编写查询顺序,我尝试如下,但没有运气。

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

我得到了结果,但userProfilePicture表的结果不是desc。

请提供解决方案

2 个答案:

答案 0 :(得分:6)

关联更新您的订单,如下所示

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

答案 1 :(得分:4)

来自Sequelize官方文档:

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

通过参考上述语法,更新您的订单选项,如下所示

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

    }
   ],
   order: [['profileImages','id', 'desc']]
] }

官方文件:http://docs.sequelizejs.com/manual/tutorial/querying.html#ordering

请参阅此主题以获取更多解决方案:https://github.com/sequelize/sequelize/issues/4553