【问题标题】:Passing a Closure with a variable to where method in Laravel query builder将带有变量的闭包传递给 Laravel 查询构建器中的 where 方法
【发布时间】:2020-12-22 12:07:56
【问题描述】:

根据 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', $q)
                      ->where('votes', '>', 50);
            })
            ->get();

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

【问题讨论】:

    标签: laravel laravel-query-builder


    【解决方案1】:

    您需要使用use() 函数将数据传递给closer 参考链接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();
    

    【讨论】:

      猜你喜欢
      • 2016-12-19
      • 1970-01-01
      • 2017-01-30
      • 2015-06-05
      • 1970-01-01
      • 2020-07-18
      • 1970-01-01
      • 1970-01-01
      • 2017-04-10
      相关资源
      最近更新 更多