排序

order 需要一个条目的数组来排序查询或者一个 sequelize 方法.一般来说,你将要使用任一属性的 tuple/array,并确定排序的正反方向.

  1. Subtask.findAll({
  2. order: [
  3. // 将转义标题,并根据有效的方向参数列表验证DESC
  4. ['title', 'DESC'],
  5. // 将按最大值排序(age)
  6. sequelize.fn('max', sequelize.col('age')),
  7. // 将按最大顺序(age) DESC
  8. [sequelize.fn('max', sequelize.col('age')), 'DESC'],
  9. // 将按 otherfunction 排序(`col1`, 12, 'lalala') DESC
  10. [sequelize.fn('otherfunction', sequelize.col('col1'), 12, 'lalala'), 'DESC'],
  11. // 将使用模型名称作为关联的名称排序关联模型的 created_at.
  12. [Task, 'createdAt', 'DESC'],
  13. // Will order through an associated model's created_at using the model names as the associations' names.
  14. [Task, Project, 'createdAt', 'DESC'],
  15. // 将使用关联的名称由关联模型的created_at排序.
  16. ['Task', 'createdAt', 'DESC'],
  17. // Will order by a nested associated model's created_at using the names of the associations.
  18. ['Task', 'Project', 'createdAt', 'DESC'],
  19. // Will order by an associated model's created_at using an association object. (优选方法)
  20. [Subtask.associations.Task, 'createdAt', 'DESC'],
  21. // Will order by a nested associated model's created_at using association objects. (优选方法)
  22. [Subtask.associations.Task, Task.associations.Project, 'createdAt', 'DESC'],
  23. // Will order by an associated model's created_at using a simple association object.
  24. [{model: Task, as: 'Task'}, 'createdAt', 'DESC'],
  25. // 嵌套关联模型的 created_at 简单关联对象排序
  26. [{model: Task, as: 'Task'}, {model: Project, as: 'Project'}, 'createdAt', 'DESC']
  27. ]
  28. // 将按年龄最大值降序排列
  29. order: sequelize.literal('max(age) DESC')
  30. // 按最年龄大值升序排列,当省略排序条件时默认是升序排列
  31. order: sequelize.fn('max', sequelize.col('age'))
  32. // 按升序排列是省略排序条件的默认顺序
  33. order: sequelize.col('age')
  34. // 将根据方言随机排序 (而不是 fn('RAND') 或 fn('RANDOM'))
  35. order: sequelize.random()
  36. })