Marko Mijailovic
Marko Mijailovic

Reputation: 431

Laravel 4.2 subquery using Query Builder

How to make this MySQL query in Query Builder?

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

What I've tried up to now is the following:

$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();

With this, I get the single 'Instance' row (and there are 4 of them) with count of 'Stations' the instance is monitoring, but I need all the instances, and if there are no stations that that instance is monitoring, the station_count should be 0.

Upvotes: 1

Views: 646

Answers (1)

Marko Mijailovic
Marko Mijailovic

Reputation: 431

Found a solution:

$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();

Upvotes: 1

Related Questions