gpt4 book ai didi

node.js - 关联 HasMany 有效但 HasOne 无效

转载 作者:行者123 更新时间:2023-12-03 22:34:33 24 4
gpt4 key购买 nike

我在 GraphQL Cars 和 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',
});
}
汽车.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 则没有。知道这是为什么吗?
任何提示将永远感激。
谢谢

最佳答案

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

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

关于node.js - 关联 HasMany 有效但 HasOne 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62748350/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com