使用Query Builder的Laravel 4.2子查询

时间:2015-11-02 15:43:04

标签: php mysql laravel

如何在Query Builder中进行MySQL查询?

SELECT traction_instances.*, 
           (SELECT COUNT(station_id) 
              FROM traction_stations 
             WHERE traction_instances.instance_id = traction_stations.monitoring_instance) as `count stations`
FROM traction_instances

我迄今为止所做的尝试如下:

$instances = DB::connection('monitors')->table(DB::raw('traction_instances as ti, traction_stations as ts'))
            ->select(array('ti.instance_id', 'ti.status', 'ti.cpu_usage', DB::raw('count(ts.station_id) as station_count')))
            ->where(DB::raw('ti.instance_id'), '=', DB::raw('ts.monitoring_instance'))
            ->get();

有了这个,我得到了单一的实例'行(并且其中有4个)具有'站点'实例正在监视,但我需要所有实例,如果没有该实例正在监视的站,则station_count应为0。

1 个答案:

答案 0 :(得分:1)

找到解决方案:

$instances = DB::connection('monitors')->table('traction_instances as ti')
            ->where('ti.instance_type', 'Audio Stream Processor')
            ->select(DB::raw('ti.*, (SELECT COUNT(*) FROM traction_stations AS ts WHERE ti.instance_id = ts.monitoring_instance) AS station_count'))
            ->get();