Reputation: 16333
Is there a way in Laravel 4.2 to join two tables using Eloquent alone? Consider the following.
I have a games table:
id | slug | name
---|------|------------------
1 | g1 | Game 1
2 | g2 | Game 2
With a respective model (models/Game.php):
class Game extends Eloquent {
protected $table = 'games';
protected $hidden = array();
public function teams() {
return $this->hasMany('Team');
}
}
I have a teams table where each team is associated to a game:
id | slug | name | game_id
---|------|--------------|--------
1 | t1 | Team 1 | 1
2 | t2 | Team 2 | 1
3 | t3 | Team 3 | 2
4 | t4 | Team 4 | 2
And it's model (models/Team.php):
class Team extends Eloquent {
protected $table = 'teams';
protected $hidden = array();
public function game() {
return $this->belongsTo('Game');
}
}
Now what I want to do, is generate a table of the teams within the system (There could be thousands) along with it's associated game joined up on teams.game_id
= games.id
.
id | slug | name | game
---------------------------
1 | t1 | Team 1 | Game 1
2 | t2 | Team 2 | Game 1
3 | t3 | Team 3 | Game 2
4 | t4 | Team 4 | Game 2
I can get this working using Eloquent by simply grabbing all teams using Team:all()
, passing this to my view and then doing the following:
<h1>Teams</h1>
@if (isset($teams) && $teams->count() > 0)
<table class="table table-striped table-hover table-bordered">
<tr>
<th>#</th>
<th>Slug</th>
<th>Name</th>
<th>Game</th>
</tr>
@foreach ($teams as $t)
<tr>
<td>{{{ $t->id }}}</td>
<td>{{{ $t->slug }}}</td>
<td>{{{ $t->name }}}</td>
<td>{{{ $t->game->name }}}</td>
</tr>
@endforeach
</table>
@else
<p>There are currently no teams stored in the system</p>
@endif
However, with this approach I am repeatedly querying the database for the game details for every team which isn't ideal. I would ideally like to perform one query, joining games
onto teams
using only Eloquent and my defined relationships. Is there a way I can do this all in one go without having to use the query builder? I did give it a go with the following code, which seems to work but I don't feel this solution is elegant enough:
$teams = Team::leftJoin('games', function($join){
$join->on('teams.game_id', '=', 'games.id');
})
->get(array('teams.id', 'teams.slug', 'teams.name', 'games.name'));
Thanks,
Upvotes: 2
Views: 2243
Reputation: 22188
I think the Eager Loading would suit your needs. Something like:
Team::with('game')->get()
Upvotes: 3