我有两个模型,公司和员工。关联是像Company hasMany Employee。Employee belongsTo Company.
我必须将所有的公司按其关联的数量由多到少排列。
我的功能如下。
function get() {
return Company.findAndCountAll({
where: { status: Active },
include: [
{
model: Employee,
as: 'employees'
}
],
}).then((companies) => {
return companies
})
}
我可以给什么顺序,使我可以得到基于协会(雇员)计数的公司列表,降序。
请帮我解决这个问题...
我已经尝试了下面的方法,但它正在抛出错误,如 表company的FROM-clause条目的无效引用。
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
})
}
其中companies是表名。
你可以试试这个。
请替换你的 字段名 与 排序领域
function get() {
return Company.findAndCountAll({
where: { status: Active },
include: [
{
model: Employee,
as: 'employees'
}
],
order: [[sortField, 'DESC']]
}).then((companies) => {
return companies
})
}