Support the ongoing development of Laravel.io →
posted 9 years ago
Database
Last updated 2 years ago.
0

This really isn't a laravel question as much as it is an SQL question:

$games = DB::table('games')
    ->leftJoin('teams AS awayteam', 'awayteams.id', '=', 'games.away_team')
    ->leftJoin('teams AS hometeam', 'hometeams.id', '=', 'games.home_team')
    ->select('games.id','awayteam.name', 'hometeam.name')->orderBy('games.game_date')
    ->get();

You might also want to look into Eloquent scopes, since this would probably be used often, and scopes allow for encapsulating logic into your model

Last updated 2 years ago.
0

Thanks jmichaelterenin. I'm getting this error: Unknown column 'teams.name' in 'field list'

Last updated 2 years ago.
0

I forgot to change to the pseudo table name, edited it in the same reply

Last updated 2 years ago.
0

jmichaelterenin, thanks for the help. I'm only getting the home team name in the output:

[
   {
       id: "10",
       name: "Blue Team",
       game_date: "2014-10-31 13:30:00"
   },
   {
       id: "11",
       name: "Red Team",
       game_date: "2014-11-06 16:15:00"
   }
 ]
Last updated 2 years ago.
0

got it.. here is the final code:

$games = DB::table('games')
    ->leftJoin('teams AS awayteam', 'awayteams.id', '=', 'games.away_team')
    ->leftJoin('teams AS hometeam', 'hometeams.id', '=', 'games.home_team')
    ->select('games.id','awayteam.name as away', 'hometeam.name as home')->orderBy('games.game_date')
    ->get();
Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.