2014-09-26 128 views
2

是否有Laravel 4.2的方式加入單獨使用雄辯兩個表?考慮以下。Laravel聯接才用雄辯

我有一個遊戲表:

id | slug | name 
---|------|------------------ 
1 | g1 | Game 1 
2 | g2 | Game 2 

與相應型號(型號/ 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 

而且它的型號(型號/ 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 

我可以通過簡單地抓住用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 

但是,使用這種方法,我反覆查詢數據庫爲每個團隊的遊戲細節,這是不理想的。我會非常想執行一個查詢,只用雄辯和我定義的關係加入到gamesteams。有沒有辦法可以一次完成這一切,而無需使用查詢構建器?我沒有給它用下面的代碼,它似乎工作一展身手,但我不覺得這種解決方案是不夠優雅:

$teams = Team::leftJoin('games', function($join){ 
    $join->on('teams.game_id', '=', 'games.id'); 
}) 
->get(array('teams.id', 'teams.slug', 'teams.name', 'games.name')); 

感謝,

+0

你檢查預先加載? http://laravel.com/docs/4.2/eloquent#eager-loading – jbx 2014-09-26 16:11:00

+0

完美,非常感謝! – Jonathon 2014-09-26 16:13:59

+0

沒問題。這裏發佈一個答案,如果它的工作原理標誌着答案:) – jbx 2014-09-26 16:16:02

回答

3

我覺得Eager Loading會滿足您的需求。喜歡的東西:

Team::with('game')->get() 
+0

非常感謝,這樣一個簡單的答案對於這樣的長篇大論問題 – Jonathon 2014-09-26 16:22:08

+0

有時它只是被指出了正確的方向的問題。 – jbx 2014-09-27 13:40:37