绑定参数到 Db::raw laravel 查询

Posted

技术标签:

【中文标题】绑定参数到 Db::raw laravel 查询【英文标题】:Binding parameter to Db::raw laravel query 【发布时间】:2017-06-14 07:34:30 【问题描述】:

我有以下原始查询:

$results = Db::select( Db::raw("SELECT HOUR(created_at) as hour, COUNT(*) as count
                       FROM `visited`
                       WHERE created_at >= DATE_SUB(NOW(),INTERVAL 16 DAY)
                       GROUP BY HOUR(created_at)") );

我需要参数化天间隔,所以我尝试了这个:

$days = 16;
$results = Db::select( Db::raw("SELECT HOUR(created_at) as hour, COUNT(*) as count
                       FROM `visited`
                       WHERE created_at >= DATE_SUB(NOW(),INTERVAL :days DAY)
                       GROUP BY HOUR(created_at)", ["days" => $days]) );

但我收到以下错误:

“SQLSTATE[HY000]:一般错误:2031

显然绑定不起作用。我做错了什么?

【问题讨论】:

【参考方案1】:

试试这个:

$results = DB::select('SELECT HOUR(created_at) as hour, COUNT(*) as count FROM visited WHERE created_at >= DATE_SUB(NOW(),INTERVAL ? DAY) GROUP BY HOUR(created_at)', [16]);

您甚至可以使用命名绑定:

$results = DB::select('SELECT HOUR(created_at) as hour, COUNT(*) as count FROM visited WHERE created_at >= DATE_SUB(NOW(),INTERVAL :days DAY) GROUP BY HOUR(created_at)', ['days' => 16]);

不需要使用DB::raw(),只需使用DB::select() 进行简单的原始选择查询:https://laravel.com/docs/master/database#running-queries

【讨论】:

以上是关于绑定参数到 Db::raw laravel 查询的主要内容,如果未能解决你的问题,请参考以下文章

如何将参数绑定到模型上使用的 Laravel 中的原始数据库查询?

DB::raw laravel 5.4 中的数组绑定在哪里

Laravel 中的 DB Raw 查询错误

Laravel 4 无法运行整个 RAW 查询

laravel 的DB::raw() 语法使用

Laravel 查询生成器按天计算行数 SQL db::raw