【问题标题】:Sequelize BelongsToMany self reference inverse SQL QUERYSequelize BelongsToMany 自引用逆 SQL QUERY
【发布时间】:2018-11-12 06:00:34
【问题描述】:

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

案例很简单: 简而言之,我得到了反向 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.parent AND kids_parents.kid = 2;

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

【问题讨论】:

    标签: node.js express orm sequelize.js has-and-belongs-to-many


    【解决方案1】:

    我在休息并重新分析文档后发现它。发现关联上的 foreignKey: 属性与 source 实例和 相关>NOT 到目标 BUT这对我来说是令人困惑的部分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() 可以正常工作了!

    【讨论】:

      猜你喜欢
      • 2017-01-16
      • 2019-03-13
      • 1970-01-01
      • 2017-08-15
      • 2018-09-23
      • 2017-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多