0

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

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

我的功能如下,

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

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

请帮我解决这个...

我已经尝试如下。但它会引发错误,例如对表公司的 FROM 子句条目的无效引用。

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

其中公司是表名。

4

1 回答 1

0

你可以试试这个。

请将您的fieldName替换为sortField

function get() {
     return Company.findAndCountAll({
       where: { status: Active }, 
       include: [
      {
        model: Employee,
        as: 'employees'
      }
    ],
    order: [[sortField, 'DESC']]
     }).then((companies) => {
         return companies
      })
}
于 2020-05-11T06:49:18.673 回答