1

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.

Marko Mijailovic
  • 421
  • 1
  • 4
  • 17
  • Possible duplicate of [How to select from subquery using Laravel Query Builder?](http://stackoverflow.com/questions/24823915/how-to-select-from-subquery-using-laravel-query-builder) – Bogdan Nov 02 '15 at 15:50
  • I'm not sure the issue is the same. I've also tried this `$instances = DB::connection('monitors')->table('traction_instances') ->select('traction_instances.*', function($query){ $query->selectRaw('count(*) FROM traction_stations WHERE traction_stations.monitoring_instance = traction_instances.instance_id'); }) ->get();` but this gives me `strtolower() expects parameter 1 to be string, object given`. – Marko Mijailovic Nov 02 '15 at 15:55

1 Answers1

1

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();
Marko Mijailovic
  • 421
  • 1
  • 4
  • 17