我想从连接表中选择一个字段,并设置为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;
关于javascript - Sequelize : findAll() include same models 2 times with different condition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53757460/