Laravel查询构建器参数绑定

ale*_*lex 4 php binding parameterbinding laravel

我正在尝试将相同的值绑定到原始查询中的某个参数(Laravel 5.2)

//this is a non practical example ,only for clarify the question

DB::table('users as u')
->select('id')
->whereRaw('u.id > ? or u.id < ? or u.id = ?',[2,2,2])
->first();
Run Code Online (Sandbox Code Playgroud)

有没有办法一次绑定相同的参数(防止重复[2,2,2]中的值)?

tre*_*mby 7

使用命名参数.它们包含在" 数据库"页面的" 运行原始SQL查询"部分的文档中,在"使用命名绑定"子标题下.引用:

?您可以使用命名绑定执行查询,而不是使用表示参数绑定:

$results = DB::select('select * from users where id = :id', ['id' => 1]);
Run Code Online (Sandbox Code Playgroud)

在你的情况下,你应该能够运行这个:

DB::table('users as u')
    ->select('id')
    ->whereRaw('u.id > :id or u.id < :id or u.id = :id', [
        'id' => 2,
    ])
    ->first();
Run Code Online (Sandbox Code Playgroud)

但似乎Laravel抛出了QueryException这个信息Invalid parameter number.我已将此报告为错误.

如果你真的想要使用,whereRaw你可以从变量构建参数数组:

$id = 2;
DB::table('users as u')
    ->select('id')
    ->whereRaw('u.id > ? or u.id < ? or u.id = ?', [
        $id, $id, $id,
    ])
    ->first();
Run Code Online (Sandbox Code Playgroud)

或者用来array_fill为你重复这个值:

$id = 2;
DB::table('users as u')
    ->select('id')
    ->whereRaw('u.id > ? or u.id < ? or u.id = ?', array_fill(0, 3, $id))
    ->first();
Run Code Online (Sandbox Code Playgroud)

如果您不需要whereRaw,可以改为使用查询构建器的其他功能并逐位构建查询,参数来自变量:

$id = 2;
DB::table('users')
    ->select('id')
    ->where('id', '>', $id)
    ->orWhere('id', '<', $id)
    ->orWhere('id', $id')
    ->first();
Run Code Online (Sandbox Code Playgroud)

查询构建器非常强大,为了获得更复杂的逻辑,您可以嵌套闭包.有关示例,请参阅文档相关部分.