亲爱的我有模型订单与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说:


  即使它被称为HasOne关联,对于大多数1:1关系,您通常也需要BelongsTo关联,因为BelongsTo将在源上添加foreignKey,而hasOne将在目标上添加。


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

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


您的错误应得到解决。

07-24 21:56