我正在尝试将相同的值绑定(bind)到原始查询中的某个参数 (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 = ?',[$id, $id, $id])
->first();
有什么方法可以一次绑定(bind)相同的参数(防止 [$id, $id, $id]
中的值重复)?
最佳答案
使用命名参数。它们包含在 Running Raw SQL Queries section of the Database page 的文档中,在副标题“使用命名绑定(bind)”下。引用:
Instead of using
?
to represent your parameter bindings, you may execute a query using named bindings:$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举一些例子。
关于php - Laravel 查询生成器多次绑定(bind)参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35960535/