在laravel上使用多个连接参数进行查询构建

时间:2018-05-23 16:58:34

标签: sql laravel eloquent

这是sql查询:

select tags.desc as areas,
    COUNT(planificacion_info.id_area) as cantidad_intervenciones,
    SUM(CASE WHEN planificacion_info.tipo_geometria = 'Polygon' and 
        planificacion_info.estado = true THEN 1 ELSE 0 END) as poligonos, 
    SUM(CASE WHEN planificacion_info.tipo_geometria = 'LineString' and 
        planificacion_info.estado = true THEN 1 ELSE 0 END) as lineas, 
    SUM(CASE WHEN planificacion_info.tipo_geometria = 'Point' and planificacion_info.estado = true THEN 1 ELSE 0 END) as puntos,
    min(planificacion_info.created_at::time) as hora from "tags" 
left join 
    "planificacion_info" on "planificacion_info"."id_area" = "tags"."id_tag"   and 
        "tags"."estado" = true and 
        "planificacion_info"."estado" = true and planificacion_info.created_at::Date = ('2018-03-09')
where 
    tags.grupo = 'area'
group by "tags"."desc"

我需要将它解析为Query Build,我有它但它无法正常工作:

$areas = \DB::table('tags')
        ->leftJoin('planificacion_info', function($query) use($fecha){
            $query->on('planificacion_info.id_area', '=', 'tags.id_tag')
            ->where('tags.grupo','=','area')
            ->where('tags.estado','=','true')
            ->where('planificacion_info.estado','=','true')
            ->where(DB::raw('planificacion_info.created_at::Date'), '=', $fecha);
        })
        ->selectRaw("tags.desc as areas, COUNT(planificacion_info.id_area) as cantidad_intervenciones, SUM(CASE WHEN planificacion_info.tipo_geometria = 'Polygon' and planificacion_info.estado = true THEN 1 ELSE 0 END) as poligonos,
        SUM(CASE WHEN planificacion_info.tipo_geometria = 'LineString' and planificacion_info.estado = true THEN 1 ELSE 0 END) as lineas,
        SUM(CASE WHEN planificacion_info.tipo_geometria = 'Point' and planificacion_info.estado = true THEN 1 ELSE 0 END) as puntos,
        min(planificacion_info.created_at::time) as hora")
->groupBy('tags.desc');

我在连接句中看到了问题。 这不正常。 感谢。

结果如下:

[ { "areas":"Ambiente y Espacio P\u00fablico",
    "cantidad_intervenciones":"0",
    "poligonos":"0",
    "lineas":"0",
    "puntos":"0",
    "hora":null
  },
  { "areas":"Arbolado",
    "cantidad_intervenciones":"0",
    "poligonos":"0",
    "lineas":"0",
    "puntos":"0",
    "hora":null
   }, ...

我认为这条线无效:

->where('tags.grupo','=','area')

1 个答案:

答案 0 :(得分:0)

在原始查询中,where()约束超出了leftJoin()

$areas = \DB::table('tags')
    ->leftJoin('planificacion_info', function($query) use($fecha) {
        ...
    })
    ->where('tags.grupo','=','area')
    ->selectRaw(...)
    ->groupBy('tags.desc');