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

使用 Laravel 的查询生成器示例是否可以将变量传递给此函数:

$someVariable = 1;

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

函数似乎无法访问自身以外的变量。我得到一个错误: undefined variable :$someVariable

最佳答案

对于该函数之外的变量,您需要在函数后使用“use”关键字。如果 $someVariable 是您要使用的那个,这应该可以工作。

$someVariable = 1;

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

https://stackoverflow.com/questions/46436176/

相关文章:

python - AWS Lambda 压缩文件命令

node.js - 在 Node.js 中生成唯一 ID 的最佳方法是什么?

php - 删除 wordpress 站点中超过 2 年的帖子

apache-kafka - Zookeeper 安装在 Windows 10 上不起作用

arrays - Perl:在哈希数组中找到最大值和最小值

regex - 如何提取ansible变量中的最后一个数字

amazon-web-services - 如何在不使用 AutoScaling 的情况下使用 aw

arrays - 测试值是否在列表/数组中 (Ti-Basic)

python-2.7 - 如何删除回复键盘( Telegram Bot )

typescript - TypeScript 有 toString() 版本吗