node.js - Sequelize BelongsToMany 自引用反向 SQL QUERY

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

大家好,希望您今天过得愉快。我在互联网上进行了搜索,这是我最后的希望。希望一些美丽的灵魂能向我解释为什么会发生这种情况,因为我无法从堆栈溢出的文档或其他问答中了解这种情况。

这个案例很简单: 简而言之,我得到了反向 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/

相关文章:

node.js - 我应该在插入到 MongoDB 之前解析 JSON 数据吗?

javascript - JSON.stringify = 非法访问

javascript - nodejs - 如何处理返回循环结构 JSON 的 API

c# - 在需要执行 C# 应用程序的 Ubuntu 上运行的 Node 服务器 - 如何?

javascript - Node.js + MongoDB 检查电子邮件是否已存在于数据库中

node.js - 在 Node/Express 服务器中使用 async/await 是个坏主意吗?

node.js - Express.js Catch All 路由不适用于 AWS EC2

php - 学说 2 @joincolumns

ASP.NET 数据集与业务对象/ORM

java - 如何在 hibernate 中建立友谊关系?