【问题标题】:Lumen whereRaw with Prepared Statement Returns NothingLumen whereRaw 与 Prepared 语句不返回任何内容
【发布时间】:2019-12-03 11:20:52
【问题描述】:

我正在尝试使用此查询从数据库中获取值

$vouchers = MerchantVoucher::where([
            'merchant_id' => $this->merchant->id,
            'code' => $voucherCode
        ])
        ->whereRaw("
            (
                (valid_from between '{$voucherValidFrom}' and '{$voucherValidTo}' ) || 
                (valid_to between '{$voucherValidFrom}' and '{$voucherValidTo}')
            )"
        )
        ->count();

通过这个查询,我得到了预期的结果,它为行数返回一个。 我尝试使用以下查询的 Prepared Statement 优化查询

    $vouchers = MerchantVoucher::where([
        'merchant_id' => $this->merchant->id,
        'code' => $voucherCode
    ])
    ->whereRaw("
        ( 
            (valid_from between '?' and '?' ) || 
            (valid_to between '?' and '?' ) 
        )", 
        [
            $voucherValidFrom, 
            $voucherValidTo, 
            $voucherValidFrom, 
            $voucherValidTo
        ]
    )
    ->count();

当我使用这个查询时,它返回 0。

有人对此有解释吗?提前谢谢你!

非 PHP 用户的原始 Sql 比较

 select count(*) from `merchant_vouchers` where (`merchant_id` = ? and `code` = ?) and 
                (
                    (valid_from between '2019-12-03 11:36:35' and '2019-12-10 11:36:35' ) || 
                    (valid_to between '2019-12-03 11:36:35' and '2019-12-10 11:36:35')
                ) and `merchant_vouchers`.`deleted_at` is null

返回 1

  select count(*) from `merchant_vouchers` where (`merchant_id` = ? and `code` = ?) and 
                ( 
                    (valid_from between '?' and '?' ) || 
                    (valid_to between '?' and '?' ) 
                ) and 
                `merchant_vouchers`.`deleted_at` is null

返回 0

使用的框架:流明

数据库:MySQL

【问题讨论】:

  • 目前无法验证我的假设,但我认为您需要删除标识符周围的引号:valid_from between ? and ?
  • @Fitzi 你的假设很好地解决了我的问题 :),谢谢!
  • 那我会回答的

标签: php mysql lumen


【解决方案1】:

您需要删除占位符周围的引号: valid_from between ? and ?

【讨论】: