[英]Sequelize: findAll() include same models 2 times with different condition
我想从联接表中选择一个字段,并设置为2个具有不同条件的输出字段。
表员工:
---------------
empId | name
---------------
001 | James
002 | Alex
003 | Lisa
---------------
表EmpDate:
------------------------------
empId | dateType | date
------------------------------
001 | REG | 2018-01-01
001 | TMN | 2018-12-31
002 | TMN | 2018-02-01
003 | REG | 2018-01-01
------------------------------
所需输出:
----------------------------------------
empId | name | regisDate | TermDate
----------------------------------------
001 | James | 2018-01-01 | 2018-12-31
002 | Alex | | 2018-02-01
003 | Lisa | 2018-01-01 |
----------------------------------------
这是我的SQL脚本(在MySQL工作台上可以正常工作)。
SELECT emp.empId
, emp.name
, reg.date AS regisDate
, tmn.date AS termDate
FROM Employee AS emp
LEFT JOIN EmpDate AS reg
ON emp.empId = reg.empId
LEFT JOIN EmpDate AS tmn
ON emp.empId = tmn.empId
WHERE reg.dateType = 'REG'
AND tmn.dateType = 'TMN'
这是我当前的Sequelize代码(由于它导致3个输出字段,因此仍无法选择所需的数据)。
exports.getEmployeeData = () => {
const emp = db.Employee
const empDate = db.EmpDate
return emp.findAll({
raw: true,
attributes: [ 'empId', 'name', 'EmpDates.date' ],
include: [{
required: false,
model: empDate,
attributes: [],
where: { dateType: ['REG', 'TMN'] }
}]
})
}
我试图像这样使用模型别名,但是没有用。
exports.getEmployeeData() = () => {
const emp = db.Employee
const empDate = db.EmpDate
return emp.findAll({
raw: true,
attributes: [
'empId',
'name',
'reg.date'
'tmn.date'
],
include: [{
required: false,
model: empDate,
attributes: [],
as: 'reg',
where: { dateType: 'REG' }
}, {
required: false,
model: empDate,
attributes: [],
as: 'tmn',
where: { dateType: 'TMN' }
}]
})
}
谁能指导我如何使用sequelize findAll()处理这种情况,或者如果我更改为sequelize query()会更好吗? 提前致谢。
您不能定义的属性reg.date
或tmn.date
。 您可以从结果对象中构造具有自定义属性的新对象。 例如,
emp.findAll({
raw: true,
attributes: [
'empId',
'name'
],
include: [{
model: empDate,
as: 'reg',
where: { dateType: 'REG' }
}, {
model: empDate,
as: 'tmn',
where: { dateType: 'TMN' }
}]
})
从以上结果中,您将得到如下结果:
[{
empId: 001,
name: 'James',
emp: {
date: '2018-01-01'
},
tmn: {
date: '2018-01-01'
}
}, {
empId: 002,
name: 'Alex',
emp: {
date: '2018-01-01'
},
tmn: {
date: '2018-01-01'
}
}]
通过该对象,您可以将结果构造为
result.regisDate = result.emp.date;
result.termDate = result.tmn.date;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.