如何使用npm Sequqlize在左连接的情况下编写嵌套条件

时间:2020-09-26 13:53:59

标签: npm sequelize.js

我正在尝试通过合并来实现左联接查询

select product.* from products
left outer join cart as c on c.prodId = product.prodId 
left outer join order as order on c.cid = p.pid
where product.secondaryId = 10 and c.cpid = 210;

我该如何编写,序列化代码。

编辑:

这是我要实现的实际MYSQL查询:

select products.* from products
left outer join Cart as cart on cart.CartId = products.CartId 
left outer join Orders as order on order.OrderId = cart.PartId
where cart.CartId = 1 and order.CustId = 12;

Sequelize端的关联

Cart.hasMany(models.Products, {as: 'Products', foreignKey: 'CartId'})
Cart.belongsTo(models.Orders, { as: 'Orders', foreignKey: 'PartId'})

Products.belongsTo(models.Cart, {onDelete: "CASCADE", foreignKey: { name: 'CartId', allowNull: false})

Products -> PrimaryKey: ProduceId

Cart -> PrimaryKey: CartId

Orders -> PrimaryKey: OrderId

1 个答案:

答案 0 :(得分:1)

首先,由于left outer join cart as c on c.prodId = product.prodId的情况,c.cpid = 210将作为普通联接工作。要么将其删除,要么将其移至on子句中:

left outer join cart as c on c.prodId = product.prodId and c.cpid = 210

从Sequelize查询开始,因为您没有显示模型定义和关联,所以我将尝试像这样进行猜测和编写(这样您就可以理解整个想法):

const products = await db.Products.findAll({
  where: {
    secondaryId: 10
  },
  include: [{
    model: db.Cart,
    required: false, // this is LEFT OUTER JOIN
    where: {
      cpid: 210
    },
    include: [{
      model: db.Order,
      as: 'Orders',
      required: false // this is LEFT OUTER JOIN
    }]
  }]
})

如果您指出模型定义和关联,那么我也可以纠正我的答案(如有必要)。