【问题标题】:Sequelize querying both parent model and included model using [Op.or]Sequelize 使用 [Op.or] 查询父模型和包含模型
【发布时间】:2021-06-08 09:00:02
【问题描述】:

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

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

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

当我执行以下查询时,它返回一个错误,提示未找到 payment.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"]],
  });

【问题讨论】:

  • 分享预订和支付模式,以及完整的错误日志

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


【解决方案1】:

我最终通过记录生成的 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"]],
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-13
    • 1970-01-01
    相关资源
    最近更新 更多