【问题标题】:How to use 'and' with 'on' condition of joins in knex如何在knex中使用'and'和'on'条件
【发布时间】:2023-03-05 06:40:01
【问题描述】:

我正在尝试生成如下查询:

select ifnull(t1.name, ‘default’) as name
from tab1 as t1
left join tab2 as t2 
 on t1.id=t2.id and t2.code=“someValue”

这是我在 knex 中写的:

var query = knex().from(’tab1’).join(’tab2', function() {

    this.on('tab1.id', '=', 'tab2.id').andOn('tab2.code', '=', 'someValue')
}, 

‘left')
.column([

knex.raw(‘IFNULL(tab1.name, "no name") as name')

]);

这不会执行,因为它将“someValue”视为一列。 在这种情况下如何应用“和”条件?

【问题讨论】:

    标签: mysql knex.js


    【解决方案1】:
    var query = knex().from('tab1').join('tab2', function() {
       this.on('tab1.id', '=', 'tab2.id')
       .on('tab2.code', '=', knex.raw('?', ['someValue']))
    }, 'left')
    .column([knex.raw('IFNULL(tab1.name, "no name") as name')]);
    

    使用 knex.raw 将 someValue 作为字符串引用就可以了。 希望这对某人有所帮助。

    【讨论】:

    • Maaan,拯救了我的夜晚 ;-) 谢谢!
    【解决方案2】:

    没有详细记录,但您现在可以使用 onVal 及其任何和/或变体。

    所以,而不是

    .on('tab2.code', '=', knex.raw('?', ['someValue']))
    

    你可以简单地写:

    const query = knex()
      .from('tab1')
      .join('tab2', function() {
         this.on('tab1.id', '=', 'tab2.id')
         this.andOnVal('tab2.code', '=', 'someValue')
    }, 'left')
    .column([knex.raw('IFNULL(tab1.name, "no name") as name')]);
    

    【讨论】:

    • 我在文档上找不到它。谢谢!你怎么知道这件事?你读过他们的源代码,不是吗?
    • objection 主要是对 knex 的封装,这些辅助方法直接来自 knex。在 0.16.1 中添加:Added onVal and the associated not / and / or methods 我的建议是还检查 knex 文档以获取其他方法。他们很可能也可以提出异议。
    【解决方案3】:

    我必须使用knex.raw('?', ['someValue']) 而不是knex.raw('someValue')

    对我来说(使用 Knex 0.13.0)接受的解决方案 .on('tab2.code', '=', knex.raw('someValue') 产生了查询: tab2.code = someValue不带引号) 然后导致Unknown column someValue 错误。

    使用.on('tab2.code', '=', knex.raw('?', ['someValue'])) 生成预期的tab2.code = 'someValue'带引号)将tab2.code 与字符串文字而不是列进行比较。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-12
      • 2012-06-04
      • 2019-01-06
      • 2018-04-30
      相关资源
      最近更新 更多