【问题标题】:Sequelize Or condition in JoinJoin 中的 Sequelize 或条件
【发布时间】:2020-11-25 16:23:32
【问题描述】:

我正在尝试使用带有自定义连接条件的 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

我不知道有没有办法做到这一点。

【问题讨论】:

  • 获取所有活跃帖子是否有意义,即使它们与某个用户无关?
  • 这只是一个例子,我想将 AND 替换为 OR

标签: javascript node.js orm sequelize.js


【解决方案1】:

您不能使用 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`

【讨论】:

    猜你喜欢
    • 2010-11-04
    • 1970-01-01
    • 2017-05-07
    • 2016-12-02
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    相关资源
    最近更新 更多