gpt4 book ai didi

jquery - Sequelize 关联 On 或 ON

转载 作者:行者123 更新时间:2023-11-29 17:54:56 24 4
gpt4 key购买 nike

亲爱的,我的模型订单与 OrderHasWarranty 模型关联

所以 OrderHasWarranty 有 2 个外键,我需要 Sequelize 来检查这两个外键的包含(不使用 where 条件)

所以我在订单模型中使用了以下关联

Order.hasOne(models.OrderHasWarranty,{foreignKey:"orderId"});
Order.hasOne(models.OrderHasWarranty,{foreignKey:"warrantyFromOrderId"});

原始查询给我:

LEFT OUTER JOIN `order_has_warranties` AS `OrderHasWarranty` 
ON `Order`.`id` = `OrderHasWarranty`.`warrantyFromOrderId`
WHERE `Order`.`id` = '25459';

基本上我需要的是使用关联转换以下查询

LEFT OUTER JOIN `order_has_warranties` 
AS `OrderHasWarranty` ON `Order`.`id` = `OrderHasWarranty`.`warrantyFromOrderId`
OR `Order`.`id` = `OrderHasWarranty`.`orderId` WHERE `Order`.`id` = '25459';

所以我需要在关联中使用 OR 条件,我尝试使用 hasMany 但没有运气

谢谢

最佳答案

我认为您无法得到您想要的东西,但我很确定进行以下更改可以为您带来所需的结果:

为关系添加别名(您可以选择更合适的别名)

Order.hasOne(models.OrderHasWarranty,{as: "warranty1", foreignKey:"orderId"});
Order.hasOne(models.OrderHasWarranty,{as: "warranty2", foreignKey:"warrantyFromOrderId"});

然后,您可以将它们都包含在搜索中,如下所示:

Order.find({
where: {
id: 25459
},
include: ['warranty1', 'warranty2']
}).then(...).catch(...);

这会产生这样的结果:

LEFT OUTER JOIN `order_has_warranties` AS `warranty1` 
ON `Order`.`id` = `OrderHasWarranty`.`orderId`
LEFT OUTER JOIN `order_has_warranties` AS `warranty2`
ON `Order`.`id` = `OrderHasWarranty`.`warrantyFromOrderId`
WHERE `Order`.`id` = '25459'

编辑:您报告的错误可能是由于使用 hasOne 方法声明关联而导致的。 Sequelize Doc说:

Even though it is called a HasOne association, for most 1:1 relations you usually want the BelongsTo association since BelongsTo will add the foreignKey on the source where hasOne will add on the target.

因此,还添加 belongsTo 关联,如下所示:

OrderHasWarranty.belongsTo(models.Order, {as: "warranty1", foreignKey:"orderId"});
OrderHasWarranty.belongsTo(models.Order, {as: "warranty2", foreignKey:"warrantyFromOrderId"});

您的错误应该已解决。

关于jquery - Sequelize 关联 On 或 ON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48939029/

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