Laravel中Eloquent执行原生SQL语句,使用paginate分页

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/NeptuneClouds/article/details/87796604

写在前面:最近在写一个小栗子,其中要关联三四张表,其中还有两张表是根据第三张表里的字段来联合查询的

投诉记录表

主键 投诉者 被投诉者 投诉方向 投诉类型主键 投诉原因

投诉类型表

主键 投诉类型 说明

客户表

主键 .....................

商家表

主键 ....................

laravel中的paginate分页很好用,但如果直接用DB运行SQL语句,并不能使用paginate。知道在SQL里有选择结构,但又想用paginate

所以

$page=self::join('complain_type','complain_type.id','=','complaint_rerord.complaint_type')->join('images','images.id','=','complaint_rerord.images_id')->select(DB::raw("complaint_rerord.id, (case when direction=0 then (select name from customer where id = defendant) else (select name from business where id = defendant) end) defendant, (case when direction=0 then (select name from business where id = plaintiff) else (select name from customer where id = plaintiff) end) plaintiff, complaint_rerord.complaint_reason, images.paths, complain_type.name, complaint_rerord.created_at, complaint_rerord.updated_at"))->paginate(10);

这样就可以实现了

SQL case when then用法

case具有两种格式。简单函数和搜索函数。

简单函数

case sex when '0' then '男' else '女' end

搜索函数

case when sex = '1' then '男' when sex = '0' then '女' end

两种写法,可以实现相同的功能。简单函数的写法比较简洁,但是和搜索函数相比,功能方面会有些限制,比如写判定式。

注意:case函数只返回第一个符合条件的值,剩下的case部分将会被自动忽略。

比如说,你永远无法得到“鱼”这个结果
case when animal in ('a','b') then '猫' when animal in ('a') then '鱼' else '其他' end

实例演示:将count与case结合使用,可以实现分段统计。

student

----------------------------------------------------

 id         name       sex(0:男,1:女)         age        

---------------------------------------------------- 

如果现在希望将上表中各种性别的人数进行统计,sql语句如下:

select count(case when s.sex=0 then 1 end)男性, count(case when s.sex=1 then 1 end)女 from student as s;

--------------------------------------------------------

        男                      女 

       50                      45

--------------------------------------------------------

猜你喜欢

转载自blog.csdn.net/NeptuneClouds/article/details/87796604