簡體   English   中英

Join 中的 Sequelize 或條件

[英]Sequelize Or condition in Join

我正在嘗試使用自定義連接條件對 Sequelize ORM 進行查詢。

有一個例子:

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

這是連接條件的結果:

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

我想要做的是將AND條件替換為OR並觀察如下內容:

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

我不知道是否有辦法做到這一點。

您不能使用 OR 將條件添加到 JOIN 條件。 您只能添加可以使用 OR 的其他外部條件。

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

這個查詢在 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`

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM