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

Laravel子查询传递动态参数问题:如何传入多个参数?

解决Laravel查询闭包传递动态参数的问题

嘿,我来帮你搞定这个问题~

首先得明确:Laravel的查询构造器在调用where方法里的闭包时,只会自动传入$query对象作为唯一参数,所以你直接给闭包定义第二个$status参数的写法是行不通的——Laravel根本不会给这个参数传值,自然会报错。

正确的实现方式:用use关键字捕获外部变量

PHP的匿名函数可以通过use语法继承外部作用域的变量,这样就能在闭包里使用动态的$status了。修改后的代码如下:

$status = '17';
DB::table('asset_status_tracker')
    ->where('asset_status_tracker.request_id', '=', $request_id)
    ->where(function($query) use ($status) { // 通过use引入外部的$status变量
        $query->where('asset_status_tracker.status_after', '=', $status)
              ->orWhere('asset_status_tracker.status_after', '=', '20');
    })
    ->select('asset_status_tracker.status_after')
    ->first();

传递多个参数的情况

如果之后需要传递多个动态参数,只需要在use里用逗号分隔变量即可:

$status = '17';
$anotherValue = '20';
DB::table('asset_status_tracker')
    ->where('asset_status_tracker.request_id', '=', $request_id)
    ->where(function($query) use ($status, $anotherValue) {
        $query->where('asset_status_tracker.status_after', '=', $status)
              ->orWhere('asset_status_tracker.status_after', '=', $anotherValue);
    })
    ->select('asset_status_tracker.status_after')
    ->first();

注意事项

如果需要在闭包里修改外部变量的值,记得在变量前加&符号来传递引用(比如use (&$status)),不过你的场景只是读取变量,所以不需要这一步。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:24:45