问题
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