如何在 Laravel 5.1 中编写原始查询?
How to write raw query in Laravel 5.1?
我是 Laravel.I 的初学者,可以用原始格式编写查询 PHP.Now 我想用 Laravel 编写查询 framework.I 已阅读文档并尝试过:
原始 PHP:
SELECT count(*)/(TIMESTAMPDIFF(YEAR,'2016-01-01 00:00:00',now())+1) as avg from buyer where created_at >= '2016-01-01 00:00:00';
尝试过 Laravel:
public function index(){
//
$yrUserReg = DB::table('buyer')
-> SELECT (DB::raw (count('*')/("TIMESTAMPDIFF(YEAR,'2016-01-01 00:00:00',now())+1")))
-> AS ('avg')
-> WHERE ("created_at >= '2016-01-01 00:00:00'");
return view('userflow',compact($yrUserReg));
}
但它抛出一个错误:Division by Zero
。我找不到任何解决方案。
提前致谢。任何帮助将不胜感激!!
这是完整的构建查询:
$yrUserReg = DB::table('buyer')
->select(DB::raw("(count('*')/(TIMESTAMPDIFF(YEAR,'2016-01-01 00:00:00',now())+1)) as avg"))
->where('created_at', '>=', '2016-01-01 00:00:00')
->get();
我是 Laravel.I 的初学者,可以用原始格式编写查询 PHP.Now 我想用 Laravel 编写查询 framework.I 已阅读文档并尝试过:
原始 PHP:
SELECT count(*)/(TIMESTAMPDIFF(YEAR,'2016-01-01 00:00:00',now())+1) as avg from buyer where created_at >= '2016-01-01 00:00:00';
尝试过 Laravel:
public function index(){
//
$yrUserReg = DB::table('buyer')
-> SELECT (DB::raw (count('*')/("TIMESTAMPDIFF(YEAR,'2016-01-01 00:00:00',now())+1")))
-> AS ('avg')
-> WHERE ("created_at >= '2016-01-01 00:00:00'");
return view('userflow',compact($yrUserReg));
}
但它抛出一个错误:Division by Zero
。我找不到任何解决方案。
提前致谢。任何帮助将不胜感激!!
这是完整的构建查询:
$yrUserReg = DB::table('buyer')
->select(DB::raw("(count('*')/(TIMESTAMPDIFF(YEAR,'2016-01-01 00:00:00',now())+1)) as avg"))
->where('created_at', '>=', '2016-01-01 00:00:00')
->get();