大家好,希望您今天过得愉快。我在互联网上进行了搜索,这是我最后的希望。希望一些美丽的灵魂能向我解释为什么会发生这种情况,因为我无法从堆栈溢出的文档或其他问答中了解这种情况。
这个案例很简单: 简而言之,我得到了反向 SQL 查询。
我有这个 self 引用协会:
User.belongsToMany(User, {as: 'parents', through: 'kids_parents',foreignKey: 'parent', otherKey: 'kid'});
User.belongsToMany(User, {as: 'kids', through: 'kids_parents', foreignKey: 'kid',otherKey: 'parent'});
然后在我的 Controller 中我有这个:
User.findById(2).then((parent) => {
parent.getKids().then((kids)=> {
console.log(kids);
});
我希望从父实例中获取所有 child 。是对的吗 ?相反,我从特定的 KID id 中获取相反的所有 parent 。
SELECT `user`.`id`, `user`.`name`, `user`.`surname`, `user`.`username`, `kids_parents`.`id` AS `kids_parents.id`, `kids_parents`.`kid` AS `kids_parents.kid`, `kids_parents`.`parent` AS `kids_parents.parent` FROM `users` AS `user` INNER JOIN `kids_parents` AS `kids_parents` ON **`user`.`id` = `kids_parents`.`parent`** AND **`kids_parents`.`kid` = 2;**
并注意这一行:
user
.id
= kids_parents
.parent
AND kids_parents
.kid
= 2;
有人可以解释为什么会发生这种情况吗?我在这里缺少什么?感谢您的关注。
最佳答案
休息一下并重新分析文档后我发现了这一点。发现关联上的 foreignKey: 属性与 source 实例和 >不是到目标但是(这对我来说是令人困惑的部分)as:属性与相关>目标实例而不是源。
User(Kid).belongsToMany(User(Parents), {as:(target) 'parents', through: 'kids_parents',foreignKey(source): 'parent' (wrong!!!), otherKey: 'kid'});
因此,而不是上面的行,应该是:
User.belongsToMany(User, {as: 'parents', through: 'kids_parents',foreignKey: 'kid' , otherKey: 'parent'});
和:
User.belongsToMany(User, {as: 'kids', through: 'kids_parents', foreignKey: 'parent',otherKey: 'kid'});
现在parent.getKids()按预期工作了!
关于node.js - Sequelize BelongsToMany 自引用反向 SQL QUERY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50654515/