[英]Laravel join only using Eloquent
Is there a way in Laravel 4.2 to join two tables using Eloquent alone? Laravel 4.2中是否有一种方法可以单独使用Eloquent连接两个表? 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): 使用各自的模型(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: 我有一个teams表,其中每个团队都与游戏相关联:
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): 它是模型(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
. 现在,我要做的是生成系统内团队的表格(可能有数千个),以及与之相关的游戏,并加入了
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: 通过使用
Team:all()
抓住所有团队,并将其传递到我的视图中,然后执行以下操作,我可以使用Eloquent进行工作:
<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. 理想情况下,我想执行一个查询,仅使用Eloquent和我定义的关系将
games
加入teams
。 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, 谢谢,
I think the Eager Loading would suit your needs. 我认为“ 急切装载”将满足您的需求。 Something like:
就像是:
Team::with('game')->get()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.