Sharath
Sharath

Reputation: 2428

Specify column name in where (or) condition in sequelize

How to add or condition along with source column in below code.

Basically I am searching for a text in multiple columns. Below is the error being throws when user.name is included.

UnhandledPromiseRejectionWarning: SequelizeDatabaseError: \Unknown column 'flights.user.name' in 'where clause'

Below is the code.

const conditionObj = {
  [Op.or]: [
    {
      source: {
        [Op.like]: `%${text}%`
      }
    },
    {
      destination: {
        [Op.like]: `%${text}%`
      }
    },
    {
      "user.name": {
        [Op.like]: `%${text}%`
      }
    }
  ]
};

const list = await db.flights.findAndCountAll({
  where: conditionObj,
  attributes: [
    "id", "source", "destination"
  ],
  include: [
    {
      association: "user",
      attributes: ["id", "name", "mobile", "email"]
    },
  ]
});

Upvotes: 1

Views: 879

Answers (1)

Anatoly
Anatoly

Reputation: 22758

For associated models try to wrap field names with $ like this:

{
  "$user.name$": {
    [Op.like]: `%${text}%`
  }
}

See the Official documentation

Upvotes: 2

Related Questions