我正在使用Sequelize ,但由于我还运行除 Node.js 之外的其他服务器,因此我需要让它们共享数据库。因此,在定义一对多关系时,我需要让Sequelize使用旧的现有jointTable。
我对关联的定义如下,其中 pid
是 presentations
的主键:
this.courses.hasMany(this.presentations,
{as : 'Presentations',
foreignKey : 'cid',
joinTableName : 'course_presentations'
});
或者这个:
this.courses.hasMany(this.presentations,
{as : 'Presentations',
foreignKey : 'pid',
joinTableName : 'course_presentations'
});
我使用以下代码来检索关联的演示文稿:
app.get('/courses/presentations/:cid', function (req, res){
var cid = req.params.cid;
app.models.courses.find({where: {cid:cid}}).success(function(course){
course.getPresentations().success(function(presentations){
res.send(presentations);
});
});
});
上一个会告诉我“presentations”表中没有cid
。
后一个将给出类似这样的内容:
Executing: SELECT * FROM `courses`;
Executing: SELECT * FROM `courses` WHERE `courses`.`cid`='11' LIMIT 1;
Executing: SELECT * FROM `presentations` WHERE `presentations`.`pid`=11;
仔细检查,我发现每次都是使用cid
值来查询presentations
,这意味着只有当它们恰好共享相同的id值时,可以退回一些东西。即使对于那些人来说,这也是不正确的。
我强烈怀疑,Sequelize 没有使用我指定的 joinTable,而是仍在尝试查找原始两个表中的外键。它将 pid
视为演示文稿中 cid
的引用,这导致了此问题。
所以我想知道如何正确设置联结表,以便他们两个可以正确使用外键。
最佳答案
jointTableName : 'course_presentations'
应该是(没有 t)
joinTableName : 'course_presentations'
关于mysql - 如何使用 Node Sequelize 正确定义与现有联合表的一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19761885/