将带有变量的闭包传递给Laravel查询构建器中的where方法

问题描述

根据Laravel文档,可以通过将闭包作为第一个参数传递给orWhere方法来对“或”条件进行分组:

$users = DB::table('users')
        ->where('Votes','>',100)
        ->orWhere(function($query) {
            $query->where('name','Abigail')
                  ->where('Votes',50);
        })
        ->get();

我想要的是在查询中使用一个变量,它看起来像:

$q = $request->get('query');
$users = DB::table('users')
            ->where('Votes',100)
            ->orWhere(function($query) {
                $query->where('name',$q)
                      ->where('Votes',50);
            })
            ->get();

我试图将其作为第二个参数传递,例如:

$q = $request->get('query');
$users = DB::table('users')
            ->where('Votes',100)
            ->orWhere($q,function($query,$q) {
                $query->where('name',50);
            })
            ->get();

但是它不起作用,有什么帮助吗?

解决方法

您需要使用use()函数将数据传递到更近的位置 引用链接In PHP,what is a closure and why does it use the "use" identifier?

 $q = $request->get('query');
 $users = DB::table('users')
          ->where('votes','>',100)
          ->orWhere(function ($query) use($q) { //  use function to pass data inside
                $query->where('name',$q)
                    ->where('votes',50);
           })
           ->get();