简体   繁体   中英

Sequelize Or condition in Join

I'm trying to do a query with Sequelize ORM with custom join condition.

There is the example:

User.findAll({include: [{model: Post, where: {active: true}}]

This is the result of join condition:

INNER JOIN `posts` AS `post` ON `users`.`id` = `post`.`user_id` AND `post`.`active`=true

What I'm trying to do is replace the AND condition to OR and spect something like this:

INNER JOIN `posts` AS `post` ON `users`.`id` = `post`.`user_id` OR `post`.`active`=true

I don´t know if there is a way to do that.

You can't add conditions to a JOIN condition with OR. You can only add additional outside conditions among which you can use OR.

User.findAll({
   where: {
     [Op.or]: [
       { '$Post.somefield$': sequelize.col('some_user_field') },
       { '$Post.someotherfield$': sequelize.col('some_other_user_field') }
     ]
   },
  include: [{
    model: Post
  }
]})

This query will be like this in SQL:

SELECT * FROM USERS as `users`
INNER JOIN `posts` AS `post` ON `users`.`id` = `post`.`user_id`
WHERE
  `post`.`somefield`=`users`.`some_user_field`
 OR
  `post`.`someotherfield`=`users`.`some_other_user_field`

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