我有两个模型,公司和员工。协会就像 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
})
}
其中公司是表名。