Laravel查询构建器参数绑定

时间:2016-03-12 16:53:29

标签: php laravel binding parameterbinding

我试图将相同的值绑定到原始查询中的某个参数(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();

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

1 个答案:

答案 0 :(得分:6)

使用命名参数。它们包含在Running Raw SQL Queries section of the Database page中的文档中,在使用命名绑定的子标题下。引用:

  

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

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

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

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

但似乎Laravel抛出QueryException消息Invalid parameter number。我已将此报告为a bug

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

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

或使用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();

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

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

查询构建器功能非常强大,为了获得更复杂的逻辑,您可以嵌套闭包。有关示例,请参阅relevant section of the docs