Sequelize 使用 [Op.or] 查询父模型和包含的模型

时间:2021-03-10 12:03:35

标签: javascript sql node.js typescript sequelize.js

我想查找已支付预订费用的所有 Bookings

如果 paymentAuthorised: boolean 表中的 Booking 属性为真,则旧预订已被支付。

如果 paymentAuthorised: boolean 表上的 Payment 属性为 true 且 type: string 表上的 Payment 属性为“booking”,则新预订已被支付。

当我执行以下查询时,它返回一条错误消息,指出没有找到 Payments.paymentAuthorised。

const bookings = await db.Booking.findAll({
    include: [
      {
        model: db.Payment,
        as: "payments",
      },
    ],
    where: {
      [Op.or]: [
        {
          paymentAuthorised: { [Op.eq]: true },
        },
        {
          "$payments.paymentAuthorised$": { [Op.eq]: true },
          "$payments.type$": { [Op.eq]: "booking" },
        },
      ],
    },
    order: [["dateTime", "asc"]],
  });

1 个答案:

答案 0 :(得分:0)

我最终通过记录生成的 SQL 解决了这个问题。您需要添加以下参数:subQuery: false。因此它会生成一个 SQL 查询,其中包含 where 之前的连接。

const bookings = await db.Booking.findAll({
    include: [
      {
        model: db.Payment,
        as: "payments",
      },
    ],
    where: {
      [Op.or]: [
        {
          paymentAuthorised: { [Op.eq]: true },
        },
        {
          "$payments.paymentAuthorised$": { [Op.eq]: true },
          "$payments.type$": { [Op.eq]: "booking" },
        },
      ],
    },
    subQuery: false,
    order: [["dateTime", "asc"]],
  });
相关问题