简体   繁体   English

Laravel - 使用查询生成器函数传递变量

[英]Laravel - Pass a variable with Query Builder function

Using Laravel's query builder example is it possible to pass a variable to this function:使用 Laravel 的查询构建器示例可以将变量传递给此函数:

$someVariable = 1;

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

It seems the function cannot access the variable outside of itself.该函数似乎无法访问自身之外的变量。 I get an error: Undefined variable: $someVariable我收到一个错误:未定义的变量:$someVariable

You'll need to use the "use" keyword after your function, for variables outside of that function.对于该函数之外的变量,您需要在函数后使用“use”关键字。 If $someVariable is the one you want to use, this should work.如果$someVariable是您要使用的那个,这应该可以工作。

$someVariable = 1;

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM