【发布时间】:2016-10-27 17:26:39
【问题描述】:
所以,我终于在我的 sequelize 代码中使用了关联。或者我是这么想的。
我有表 A 关联到表 B 和表 B 关联到表 C 通过外键。我想使用 A、B 和 C 中的过滤器从 A 中获取行。如果 C 不在图片中,我会这样做:
models.A.findOne({
attributes: ['id', 'col1', 'col2'],
where: {
col1: value1,
col3: value3
},
include: [{model: models.B, required: true}]
}).then(function (result) {
res.send(result);
}).catch(function(error){
console.log(error);
res.send(error);
});
注意 col3 是表 B 中的一个字段。
现在我想做的最好写成:
models.A.findOne({
attributes: ['id', 'col1', 'col2'],
where: {
col1: value1,
col3: value3,
col5: value5
},
include: [{model: models.B, required: true}, {model: models.C, required: true}]
}).then(function (result) {
res.send(result);
}).catch(function(error){
console.log(error);
res.send(error);
});
Col5 是表 C 的一个字段。
这样做(正确地)给我一个错误:C 未连接到 A。 我知道 A 连接到 B 和 B 连接到 C,因为我在模型中定义了这些连接。但我什至无法定义跨表关联——比如 A 和 C。
首先,我不知道该怎么做,其次,关联可能包含多达 5 个表的链。当我说链时,我指的是一系列关联,而不是同一张表的并行关联。
sequelize 如何处理这种情况?
【问题讨论】:
标签: node.js associations sequelize.js model-associations