在项目中遇到一个问题,复杂的sql查询,用laravel的查询构造器,非常的不方便,各种查询条件拼接一长串拼得脑瓜疼;然后想使用原生的sql语句来查询,然后又使用不了laravel的paginate()分页方法;这时候DB::raw()方法就派上用场了!语法的原理就是把你查询的结果集当成一个临时表,然后在使用laravel的查询构造器语法进行分页处理;
例1:
$users = DB::table('users')
->select(DB::raw('count(*) as user_count, status'))
->where('status', '<>', 1)
->groupBy('status')
->get();
例2:
DB::table('someTable')
->selectRaw('count(*), min(some_field) as someMin, max(another_field) as someMax')
->get();
例3:
DB::table('someTable')->select(
array(
DB::raw('min(some_field) as someMin'),
DB::raw('max(another_field) as someMax'),
DB::raw('COUNT(*) as `count`')
)
)->get()
例4:
SELECT
(CASE WHEN (gender = 1) THEN 'M' ELSE 'F' END) AS gender_text
FROM users;
$users = DB::table('users')
->select(DB::raw("
name,
surname,
(CASE WHEN (gender = 1) THEN 'M' ELSE 'F' END) as gender_text")
);
网友评论