Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize query Or-ing where and include statements

I am trying make a Sequelize query that returns only records that match a where clause or include wheres. For example I have a user model that belongs to a person model. The user model has one field called username and the person model has a first and last name.

Example Query:

{
    "where": {
      "username": {
        "$iLike": "%s%"
      }
    },
    "include": [{
        "model": Person,
        "where": {
            "$or": [{
                "firstName": {
                    "$iLike": "%s%"
                }
            }, {
                "lastName": {
                    "$iLike": "%s%"
                }
            }]
        }
    }]
}

The query above matches records that have a username AND (firstname or lastname) matching "ilike" 's'. I am trying to achieve username OR (firstname or lastname).

I know how do use Or operators when working inside of a where but I want to use an Or on where or include. Is this possible? Do I use required false?

like image 980
Arthur Putnam Avatar asked Dec 17 '22 23:12

Arthur Putnam


1 Answers

try this:

{
where: {
  $or: [
    {
      userName: {
        $ilike: "%s%"
      }
    },
    {
      '$person.firstName$': {
        $ilike: "%s%"
      }
    },
    {
      '$person.lastName$': {
        $ilike: "%s%"
      }
    }
  ]
},
include: [
  {
    model: Person,
  }
]
}
like image 64
ManjulSigdel Avatar answered Jan 06 '23 10:01

ManjulSigdel