Laravel雄辩的查询具有JOIN和子查询

时间:2019-06-15 16:57:45

标签: mysql laravel eloquent

我必须以雄辩的Laravel(query builder)使用查询,但是我不确定如何转换它:

SELECT c.*, m.*,th.team as team_home, ta.team as team_away from schedule as c

LEFT JOIN matches as m ON m.id_match = c.match_id
LEFT JOIN teams as  th ON m.team_h = th.id_team
LEFT JOIN teams as  ta ON m.team_a = ta.id_team

WHERE c.serie_id = :sid and c.days =(

   SELECT c.days from schedule as c
   LEFT JOIN matches as m ON m.id_match = c.match_id
   WHERE c.serie_id = :sid and m.match_stato = 2 order by c.days DESC LIMIT 1

) order by c.days, th.team ASC

如您所见,它具有3个JOINS和一个子查询,而不是两个订单。如何在Eloquent中使用它?

2 个答案:

答案 0 :(得分:1)

对于这种性质的子查询,可以使用whereIn()

此外,对于子查询中的逻辑,也可以在select子句中使用order by c.days DESC LIMIT 1来代替max(c.days)

DB::table('schedule as c')
    ->join('matches as m', 'm.id_match', '=', 'c.match_id')
    ->join('teams as th', 'm.team_h', '=', 'th.id_team')
    ->join('teams as ta', 'm.team_a', '=', 'ta.id_team')

    ->where('c.serie_id', '=', $sid)
    ->whereIn('c.days', function($query) use($sid){
        $query->select('max(c.days)')
            ->from('schedule as c2')
            ->join('matches as m2', 'm2.id_match', '=', 'c2.match_id')
            ->where('c2.serie_id', '=', $sid)
            ->where('m2.match_stato', '=', 2);
    }) 
    ->select('c.*', 'm.*', 'th.team as team_home', 'ta.team as team_away')

    ->orderBy('c.days', 'asc')
    ->orderBy('th.team', 'asc')
    ->get();      

######

答案 1 :(得分:1)

我们在这里。仔细检查所有错误或逻辑,因为这是一个复杂的查询。但我希望它将为您提供正确方向的指针

DB::query()
   ->select(['c.*', 'm.*','th.team as team_home', 'ta.team as team_away'])
   ->from('schedules AS c')
   ->leftJoin('matches AS m', 'm.id_match', '=', 'c.match_id')
   ->leftJoin('teams AS th', 'm.team_h', '=', 'th.id_team')
   ->leftJoin('teams AS ta', 'm.team_a', '=', 'ta.id_team')

   ->where('c.serie_id','=',':sid')
   ->whereIn('c.days', function($q) {
       $q->select('c.days')
         ->from('schedule AS c')
         ->leftJoin('matches AS m', 'm.id_match', '=', 'c.match_id')
          ->where('c.serie_id','=',':sid')
          ->where('m.match_stato','=',2)
          ->orderBy('c.days','DESC')
          ->limit(1);
     })

    ->orderBy('c.days')
    ->get()