Sequelize query Or-ing where and include statements

蓝咒 提交于 2020-01-06 05:54:04

问题


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?


回答1:


try this:

{
where: {
  $or: [
    {
      userName: {
        $ilike: "%s%"
      }
    },
    {
      '$person.firstName$': {
        $ilike: "%s%"
      }
    },
    {
      '$person.lastName$': {
        $ilike: "%s%"
      }
    }
  ]
},
include: [
  {
    model: Person,
  }
]
}


来源:https://stackoverflow.com/questions/49837932/sequelize-query-or-ing-where-and-include-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!