You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 5.2中orWhereRaw关联查询报错,求修正方案

解决Laravel 5.2中Object of class Closure could not be converted to string错误

你的错误核心原因是Laravel 5.2里的orWhereRaw()不支持传入闭包,它仅能接收原生SQL字符串,把闭包传给它就会触发“闭包无法转为字符串”的报错。

修改方案很直接,把外层的orWhereRaw()替换为orWhere(),闭包内部的whereRaw()保留即可——因为闭包内的$query是QueryBuilder实例,完全支持whereRaw()方法:

$results = DB::table('statement_transactions AS st')
            ->join('quickbooks_transactions AS qt', function ($join) {
                $join->on('st.transaction_date', '=', 'qt.transaction_date');
                $join->on('st.transaction_type_id', '=', 'qt.transaction_type_id');
                $join->on('st.original_amount', '=', 'qt.original_amount');
                $join->on('st.balance', '=', 'qt.balance');
            })
            ->where('st.statement_id', $this->statement->id)
            ->where('st.has_match', 0)
            ->where('st.has_partial_match', 0)
            ->whereNull('st.quickbooks_transaction_id')
            ->orWhere(function ($query) {
                $query->whereRaw("LEFT(REPLACE(st.invoice_nbr, '-', ''), 5) = LEFT(REPLACE(qt.invoice_nbr, '-', ''), 5)")
                    ->whereRaw("RIGHT(REPLACE(st.invoice_nbr, '-', ''), 5) = RIGHT(REPLACE(qt.invoice_nbr, '-', ''), 5)");
            })
            ->select('st.id AS statement_transaction_id', 'qt.id AS quickbooks_transaction_id')
            ->get();

修改说明

  • orWhere()支持传入闭包,用来构建一组嵌套的OR条件,完美匹配你的需求:前面所有WHERE条件满足,或者闭包内的两个发票号部分匹配条件满足。
  • 闭包内部的whereRaw()可以正常执行原生SQL片段,实现发票号去掉横杠后前后5位匹配的逻辑。

内容的提问来源于stack exchange,提问作者hyphen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 22:06:26