【发布时间】:2014-11-21 17:05:38
【问题描述】:
在 Laravel 4.2 中有没有办法单独使用 Eloquent 连接两个表?请考虑以下内容。
我有一张游戏桌:
id | slug | name
---|------|------------------
1 | g1 | Game 1
2 | g2 | Game 2
使用各自的模型(models/Game.php):
class Game extends Eloquent {
protected $table = 'games';
protected $hidden = array();
public function teams() {
return $this->hasMany('Team');
}
}
我有一个团队表,其中每个团队都与一个游戏相关联:
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
它是模型(models/Team.php):
class Team extends Eloquent {
protected $table = 'teams';
protected $hidden = array();
public function game() {
return $this->belongsTo('Game');
}
}
现在我想做的是生成系统内的团队表(可能有数千个)以及在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
我可以使用 Eloquent 完成这项工作,只需使用 Team:all() 抓取所有团队,将其传递给我的视图,然后执行以下操作:
<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
但是,使用这种方法,我会反复查询数据库以获取每支球队的比赛详细信息,这并不理想。理想情况下,我希望执行一个查询,仅使用 Eloquent 和我定义的关系将games 加入teams。有没有一种方法可以一次性完成所有操作而无需使用查询生成器?我确实尝试了以下代码,这似乎可行,但我觉得这个解决方案不够优雅:
$teams = Team::leftJoin('games', function($join){
$join->on('teams.game_id', '=', 'games.id');
})
->get(array('teams.id', 'teams.slug', 'teams.name', 'games.name'));
谢谢,
【问题讨论】:
-
您是否检查了急切加载? laravel.com/docs/4.2/eloquent#eager-loading
-
完美,非常感谢!
-
没问题。在此处发布答案,如果有效,请标记答案:)