【问题标题】:BelongsToMany Relationship - SequelizeBelongsToMany 关系 - 续集
【发布时间】:2020-12-16 18:05:53
【问题描述】:

我在使用 sequelize + nodejs 列出具有 belongsToMany 关联的记录时遇到问题。

我有开发人员和技术表。他们之间的关系是多对多的。要创建关系,请使用名为 developers_technologies 的数据透视表。

以下是代码的要点:模型(开发人员,技术),迁移(developers_technologies)和开发人员的控制器。

https://gist.github.com/fredarend/85ff60fca70643d80301b499e871c4a6

控制器开发者的Index代码是这样的:

async index(req, res) {
const developers = await Developer.findAll({
  attributes: ['id', 'name', 'email'],
  include: [
    {
      model: Technologies,
      as: 'technologies',
      attributes: ['id', 'name'],
      through: { attributes: [] },
    },
  ],
});

return res.json(developers);}

返回:

[
    {
        "id": 25,
        "name": "Jon Doe",
        "email": "jondoe@gmail.com",
        "age": 27,
        "url_linkedin": "http://asdasdasd",
        "technologies": []
    }
]

我想知道为什么我没有收到与开发人员相关的技术,因为数据库中的 developers_technologies 表已填充并且模型中的关系正常。

编辑: 从请求生成的查询:

SELECT 
"Developer"."id", 
"Developer"."name", 
"Developer"."email", 
"technologies"."id" AS "technologies.id", 
"technologies"."name" AS "technologies.name", 
"technologies->developers_technologies"."created_at" AS "technologies.developers_technologies.createdAt", 
"technologies->developers_technologies"."updated_at" AS "technologies.developers_technologies.updatedAt", 
"technologies->developers_technologies"."developer_id" AS "technologies.developers_technologies.developer_id", 
"technologies->developers_technologies"."technology_id" AS "technologies.developers_technologies.technology_id" 
FROM "developers" AS "Developer" 
LEFT OUTER JOIN ( "developers_technologies" AS "technologies->developers_technologies" 
INNER JOIN "technologies" AS "technologies" ON "technologies"."id" = "technologies->developers_technologies"."developer_id") ON "Developer"."id" = "technologies->developers_technologies"."technology_id";

亲切的问候,

【问题讨论】:

    标签: node.js api rest express sequelize.js


    【解决方案1】:

    尝试在belongToMany 关联中指明otherKey。您还指出了错误的外键。对于开发人员,它应该是developer_id,对于技术,它应该是technology_id

    模型 - 开发者

    this.belongsToMany(models.Technology, {
          foreignKey: 'developer_id',
          otherKey: 'technology_id',
          through: 'developers_technologies',
          as: 'technologies',
        });
    

    模型 - 技术

    this.belongsToMany(models.Developer, {
          foreignKey: 'technology_id',
          otherKey: 'developer_id',
          through: 'developers_technologies',
          as: 'developers',
        });
    

    【讨论】:

    • 我加了,同样的返回还在继续:/很奇怪..
    • 查看生成的 SQL 查询并将其添加到您的问题中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-03
    • 2018-05-19
    • 1970-01-01
    • 2019-10-01
    • 2015-02-22
    • 2014-12-30
    相关资源
    最近更新 更多