续集属于许多自引用逆SQL查询



大家好,希望你的一天很棒。我已经在互联网上搜索了所有内容,这是我的最后一条希望线。希望一些美丽的灵魂会向我解释为什么会发生这种情况,因为我无法从文档或其他问答中理解堆栈溢出这种情况。

情况很简单: 简而言之,我正在获得反向SQL查询。

我有这个自我参考关联:

User.belongsToMany(User, {as: 'parents', through: 'kids_parents',foreignKey: 'parent', otherKey: 'kid'}); 
User.belongsToMany(User, {as: 'kids', through: 'kids_parents', foreignKey: 'kid',otherKey: 'parent'});

那么在我的控制器中,我有这个:

User.findById(2).then((parent) => {
parent.getKids().then((kids)=> {
console.log(kids);
});

我希望从父实例中获取所有孩子。是吗?相反,我从特定的 KID ID 中得到了相反的所有父母。

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.parentkids_parents.kid= 2;

有人可以解释为什么会这样吗?我在这里错过了什么?感谢您的关注。

我在休息并重新分析文档后弄清楚了。找出foreignKey: atribute on the Association 与源实例相关,而不是与目标实例相关,(这对我来说是令人困惑的部分(asatribute 与目标实例相关,而不是实例相关。

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(( 按预期工作!

最新更新