流明whereRaw与准备好的语句不返回任何内容

时间:2019-12-03 11:20:52

标签: php mysql lumen

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

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

通过该查询,我得到了预期的结果,该结果针对行数返回1。 我尝试使用以下语句的“准备语句”优化查询

    $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

1 个答案:

答案 0 :(得分:1)

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