【问题标题】:Sequelize Query prepare issueSequelize Query 准备问题
【发布时间】:2020-08-25 08:43:03
【问题描述】:

我有以下原始查询需要转换为 Sequelize ORM 查询

SELECT count(*) AS count FROM user_posts AS user_posts WHERE (user_posts.source_id = '621' 和user_posts.source_type = '游戏' AND user_posts.user_id = 87 AND user_posts.post_type_id = 7 AND user_posts.archive = false) 或 user_posts.local_db_path = 'xxx-xxx-xxx';

我在 Sequelize ORM 中编写了以下查询

let result = await Post.count({
      where:{
        local_db_path:local_db_path,
        [Op.or]:[
          {
            [Op.and]:[
              { source_id:inputs.source_id },
              { source_type:MAP_SOURCE_TYPE[inputs.source_type] },
              { user_id:user.id },
              { post_type_id:7 },
              { archive:false },
            ]
          }
        ]
      }      
    });

但是这个查询在 local_db_path 和大括号条件之间添加了 AND 操作,但我需要 OR 运算符而不是 AND。

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

    您必须将 local_db_path 移至 Op.or 案例:

    let result = await Post.count({
      where: {
        [Op.or]: [
          {
            [Op.and]: [
              { source_id: inputs.source_id },
              { source_type: MAP_SOURCE_TYPE[inputs.source_type] },
              { user_id: user.id },
              { post_type_id: 7 },
              { archive: false },
            ],
          },
          {
            local_db_path: 'xxx-xxx-xxx',
          },
        ],
      },
    });
    

    【讨论】:

    • 在 Sequelize 中,连词(与其他一些运算符不同)都需要是它们绑定的对象/项目的父项。它产生了一些笨拙的条件。而且,where 属性/子句的默认值是隐式 AND 连词。
    猜你喜欢
    • 2017-07-23
    • 2018-01-10
    • 2012-10-12
    • 2013-08-23
    • 2019-09-06
    • 1970-01-01
    • 1970-01-01
    • 2015-12-08
    • 2014-09-16
    相关资源
    最近更新 更多