laravel complex sql query

时间:2017-05-09 13:00:47

标签: mysql sql laravel eloquent

我有3张桌子:航空公司,航班,信息。

  1. 每家航空公司都有很多"飞行。
  2. 每个航班都有很多"的相关信息。
  3. 每家航空公司都有很多通过"的相关信息。
  4. 我需要查询查询db或eloquent ORM来获取此信息:

    ---------------------------------------------------------------
      id  | airline_name | infos_count | infos_canceled | infos_late
    ---------------------------------------------------------------
      1     b_airline           6             2            5(minutes)   
    
    
    airline_name: name of airline company
    
    infos_count: count of info which belong to flight table and this airline company
    
    infos_canceled: count of info where (status=0)
    
    infos_canceled: sum of (subtract time of schedule_time)
    

    Tables diagram

    我使用变换器类做了这个,但我希望这使用查询.. 任何帮助请... ..

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT A.id
     , A.name AS 'airline_name'
     , COUNT(I) AS 'infos_count'
     , COUNT(CASE WHEN I.status = 'Canceled' THEN 1 ELSE 0 END) AS 'infos_canceled'
     , COUNT(CASE WHEN I.status = 'Late' THEN 1 ELSE 0 END) AS 'infos_late'
  FROM airlines A
  INNER JOIN flights F
          ON A.id = f.airline_id
  INNER JOIN infos I
          ON F.id = I.flight_id

答案 1 :(得分:0)

感谢@Jake的回答,我的回答:

Airline::select([
                'airlines.id',
                'airlines.name',
                \DB::raw('count(*) as flight_count'),
                \DB::raw('CAST(SUM(i.time-i.schedule_time) AS time) as flight_late'),
                \DB::raw('count(CASE WHEN i.status = 0 THEN 1 ELSE NULL END ) as canceled_count')
            ])
                ->join('flights as f', 'f.airline_id', '=', 'airlines.id')
                ->join('infos as i', 'i.flight_id', '=', 'f.id')
                ->groupBy('airlines.id');