【问题标题】:Sequelize - ORDER BY count of associationsSequelize - 按关联计数排序
【发布时间】:2020-05-11 06:03:33
【问题描述】:

我有两个模型,Company 和 Employee。协会就像 Company hasMany Employee。员工属于公司。

我必须按关联的数量按降序列出所有公司。

我的功能如下,

function get() {
     return Company.findAndCountAll({
       where: { status: Active }, 
       include: [
      {
        model: Employee,
        as: 'employees'
      }
    ],
     }).then((companies) => {
         return companies
      })
}

我可以按顺序给出什么,以便我可以根据协会(员工)的数量按降序获得公司列表。

请帮帮我...

我已经尝试如下。但它会抛出类似 invalid reference to FROM-clause entry for table Companies 之类的错误。

function get() {
     return Company.findAndCountAll({
       where: { status: Active }, 
       include: [
      {
        model: Employee,
        as: 'employees'
      }
    ],
     attributes: [
        [Sequelize.literal('(SELECT COUNT(*) FROM employees WHERE employees.company_id = companies.id)'), 'employeesCount']
    ],
    order: [[Sequelize.literal('employeesCount'), 'DESC']],
     }).then((companies) => {
         return companies
      })
}

company 是表名。

【问题讨论】:

    标签: node.js sequelize.js sql-order-by associations has-many


    【解决方案1】:

    你可以试试这个。

    请将您的 fieldName 替换为 sortField

    function get() {
         return Company.findAndCountAll({
           where: { status: Active }, 
           include: [
          {
            model: Employee,
            as: 'employees'
          }
        ],
        order: [[sortField, 'DESC']]
         }).then((companies) => {
             return companies
          })
    }
    

    【讨论】:

    • 问题是company表中没有employees_count字段
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多