Laravel 查询构建器参数绑定

2022-01-04 00:00:00 binding php laravel parameterbinding

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

I'm trying to bind the same value to some parameter in a raw query (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]中的值重复)?

is there any way to bind the same parameters at once(prevent duplicating values in [2,2,2])?

推荐答案

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

Use named parameters. They're covered in the documentation in the Running Raw SQL Queries section of the Database page, under the subheading Using Named Bindings. Quoting:

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

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]);

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

In your case you ought to be able to run this:

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.我已将此报告为一个错误.

But it seems Laravel throws a QueryException with the message Invalid parameter number. I've reported this as a bug.

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

If you really want to use whereRaw you could instead build your array of parameters from a variable:

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

或者使用array_fill重复对您的价值:

Or use array_fill to repeat the value for you:

$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,您可以使用查询构建器的其他功能并一点一点地构建查询,参数来自变量:

If you don't need whereRaw you can instead use other features of the query builder and build the query bit by bit, with the parameter coming from a variable:

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

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

The query builder is quite powerful, and to get more complicated logic you can nest closures. See the relevant section of the docs for some examples.

相关文章