【问题标题】:Associations HasMany works but HasOne does not关联 HasMany 有效,但 HasOne 无效
【发布时间】:2020-07-08 10:13:11
【问题描述】:

我在 GraphQL Cars and Brands 中定义了两个模型(它们的关联是cars.brand_id =brands.id)。 该架构仅在我定义时才有效:

Cars.hasMany(models.brands, {
 sourceKey: 'brand_id',
 foreignKey: 'id'
})

如果我按以下方式定义它就不起作用:

Cars.hasOne(models.brands, {
 sourceKey: 'brand_id',
 foreignKey: 'id'
}),

这里我分享了更多的架构(我使用 makeExecutableSchema 来拆分文件定义):

协会:

CarBrands.js

  CarBrands.associate = models => {
    CarBrands.hasOne(models.cars, {
    foreignKey: 'brand_id',
    });
  }

Cars.js

  Cars.associate = models => {
    Cars.belongsTo(models.brands),
    Cars.hasMany(models.car_images, {
        foreignKey: {
          name: 'car_id',
          allowNull: false
        },
        onDelete: "cascade"
    });
  };

车型:

export const typeDef = `
    type Cars {
        user_id: Int!,
        title: String!,
        brands: [CarBrands!],
        car_images: [CarImages],
    }
`;

SQL 格式正确,car_images 正确返回数据,而brands 不正确。知道为什么吗? 任何提示将永远不胜感激。

谢谢

【问题讨论】:

    标签: node.js graphql sequelize.js


    【解决方案1】:

    您可以在此处找到文档 one-to-one-relationshipshttps://sequelize.org/master/manual/assocs.html#one-to-one-relationships .在文档中介绍了4个选项来定义一对一。

    试试看:

    Brands.hasOne(Cars, {
      foreignKey: 'brand_id'
    });
    Cars.belongsTo(Brands);
    

    【讨论】:

    • 您好,感谢您的回复。我确实对此进行了测试,但没有奏效。我花了很长时间试图找到问题,但没有任何效果。我现在添加了更多代码,正如您看到 car_images 查询正确返回数据,但品牌没有,知道为什么会这样吗? (SQL 格式正确)。
    猜你喜欢
    • 2016-03-17
    • 2020-11-26
    • 1970-01-01
    • 1970-01-01
    • 2016-10-08
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多