Laravel - 使用Query Builder函数传递变量

时间:2017-09-26 21:32:16

标签: php laravel

使用Laravel的查询构建器示例可以将变量传递给此函数:

$someVariable = 1;

DB::table('users')
        ->where('name', '=', 'John')
        ->orWhere(function ($query) {
            $query->where('votes', '>', $someVariable)
                  ->where('title', '<>', 'Admin');
        })
        ->get();

似乎函数无法访问自身之外的变量。我收到一个错误:未定义的变量:$ someVariable

2 个答案:

答案 0 :(得分:1)

您需要使用&#34;使用&#34;函数之后的关键字,用于该函数之外的变量。如果$someVariable是您要使用的那个,那么这应该有效。

$someVariable = 1;

DB::table('users')
->where('name', '=', 'John')
->orWhere(function ($query) use($someVariable) {
    $query->where('votes', '>', $someVariable)->where('title', '<>', 'Admin');
})->get();

答案 1 :(得分:0)

use Superglobals 

$GLOBALS["someVariable"] = 1;
DB::table('users')
->where('name', '=', 'John')
->orWhere(function ($query) {
       $query->where('votes', '>', $GLOBALS["someVariable"])
       ->where('title', '<>', 'Admin');
})
->get();