编程语言
首页 > 编程语言> > php – 将参数绑定到Db :: raw laravel查询

php – 将参数绑定到Db :: raw laravel查询

作者:互联网

我有以下原始查询:

$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]: General error: 2031

显然绑定不起作用.我究竟做错了什么?

解决方法:

试试这个:

$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

标签:php,laravel,mysql,octobercms,parameterbinding
来源: https://codeday.me/bug/20190828/1754005.html