简体   繁体   中英

Sequelize querying both parent model and included model using [Op.or]

I want to findAll Bookings where the booking has been paid.

A legacy booking has been paid if the paymentAuthorised: boolean attribute on the Booking table is true.

A new booking has been paid if the paymentAuthorised: boolean attribute on the Payment table is true and type: string attribute on the Payment table is 'booking'.

When I perform the following query it returns an error saying payments.paymentAuthorised not found.

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"]],
  });

I worked this issue out in the end by logging the generated SQL. You need to add the following parameter: subQuery: false . This is so it generates an SQL query which includes the joins before the 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"]],
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM