如何将我的SQL查询转换为laravel ORM

时间:2017-11-13 15:41:21

标签: mysql laravel

我在laravel 5中的新内容如何将此查询转换为laravel ORM

select m.nombre,c.fecha_control as primer_control,
(select control.fecha_control 
  from control 
  where m.id = control.id_mascota
  order by control.fecha_control 
  DESC limit 1) as ultimo_control
from mascota m
left join control as c on m.id = c.id_mascota
GROUP BY m.nombre

我试试这个,但它没有工作......

 DB::table('mascota as m')
        ->leftJoin('control as c','m.id','=','c.id_mascota')
        ->select('m.nombre','c.fecha_control as primer_control',
            \DB::raw('select control.fecha_control  from control 
                        where m.id = control.id_mascota
                        order by control.fecha_control 
                        DESC limit 1
                        ) as ultimo_control'))
        ->groupBy('m.id');

谢谢

1 个答案:

答案 0 :(得分:0)

我只有语法错误,它工作正常。我需要3个小时才能实现

DB::table("mascota as m")
 ->leftJoin('control as c','m.id','=','c.id_mascota')
 ->select('m.nombre','c.fecha_control as primer_control'),
    DB::raw("(select control.fecha_control 
              from control 
              where m.id = control.id_mascota
              order by control.fecha_control 
              DESC limit 1) as ult_control"))
  ->groupBy('m.id');