Home > OS >  Specify column name in where (or) condition in sequelize
Specify column name in where (or) condition in sequelize

Time:10-08

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

CodePudding user response:

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

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

See the Official documentation

  • Related