如何将此查询置于Eloquent / Laravel格式中?

时间:2015-12-13 11:03:33

标签: mysql laravel laravel-5 eloquent

我只有一个用于团队的表和两个带有指向那里的外键的字段。

DB::select('    SELECT 
                    matches.*, teams.name as home , guests.name as guest
                FROM 
                    matches
                LEFT JOIN 
                    teams
                ON 
                    teams.id = matches.home_id
                LEFT JOIN 
                    teams as guests
                ON 
                    guests.id = matches.guest_id
                ORDER BY 
                    matches.date DESC, matches.time ASC
');

1 个答案:

答案 0 :(得分:2)

以下代码可以解决这个问题:

$results = DB::table('matches')
  ->leftJoin('teams', 'teams.id', '=', 'matches.home_id')
  ->leftJoin('teams as guests', 'guests.id', '=', 'matches.guest_id')
  ->orderBy('matches.date', 'desc')
  ->orderBy('matches.time', 'asc')
  ->addSelect('matches.*', 'teams.name as home', 'guests.name as guest')
  ->get();