【问题标题】:Bookshelf andWhere / orWhere syntax problemBookshelf andWhere / orWhere 语法问题
【发布时间】:2020-08-15 11:41:30
【问题描述】:
await bookshelf
    .model('User')
    .where({ org_id: this.get('id'), isAdministrator: 1 })
    .fetchAll()
    .then...

这有效并选择具有特定org_idisAdministrator 等于1 的那些记录。

我想扩展此.where 行,使其同时选择员工和合作伙伴。我希望他遵循代码能够工作:

await bookshelf
    .model('User')
    .query({
        where: { org_id: this.get('id'), isAdministrator: 1 },
        orWhere: { org_id: this.get('id'), isAssociate: 1 },
        orWhere: { org_id: this.get('id'), isPartner: 1 }
    })
    .fetchAll()
    .then...

但是,它只选择管理员和合作伙伴,而不选择员工。我做错了什么?

【问题讨论】:

  • 您可以提供调试选项以查看正在执行的实际查询,如下所示:.fetchAll({debug:true})。但是,在完成了自己的测试之后,我发现您的代码中没有错误,并且它成功获取了 isAdministrator 为 0 和 isAssociate 为 1 的行。也许您应该分享完整的代码?或者数据库中可能缺少一行?
  • 调试后的 sql 代码如下:'select `users`.* from `users` where `org_id` = ? and `isAdministrator` = ? or (`org_id` = ? and `isAssociate` = ?)' 这对我来说很好。
  • 谢谢!这将返回:'select `users`.* from `users` where `org_id` = ? and `isAdministrator` = ? or (`org_id` = ? and `isPartner` = ?)'。所以似乎忽略了第一个orWhere...
  • 哦,有3个or子句,我没看到。问题是.query函数的参数:{ where: { org_id: this.get('id'), isAdministrator: 1 }, orWhere: { org_id: this.get('id'), isAssociate: 1 }, orWhere: { org_id: this.get('id'), isPartner: 1 } }是无效的javascript对象,因为javascript对象不能有多个相同的键。我确信有办法规避这个问题,我会将其作为答案发布。
  • 也许使用 .whereRaw 并编写正确的原始 sql 查询...

标签: javascript node.js model bookshelf.js


【解决方案1】:

问题在于.query函数的参数:

{
        where: { org_id: this.get('id'), isAdministrator: 1 },
        orWhere: { org_id: this.get('id'), isAssociate: 1 },
        orWhere: { org_id: this.get('id'), isPartner: 1 }
}

无效,因为 javascript 对象不能有多个相同的键。改为:

bookshelf.model('User').query((queryBuilder) => {
    queryBuilder
        .where({ org_id: this.get('id'), isAdministrator: 1 })
        .orWhere({ org_id: this.get('id'), isPartner: 1 })
        .orWhere({ org_id: this.get('id'), isAssociate: 1 });
    }).fetchAll({debug: true}).then(function(users){
        //...
})  

【讨论】:

    猜你喜欢
    • 2012-02-24
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-17
    • 1970-01-01
    • 2015-06-23
    相关资源
    最近更新 更多