首页 文章

Laravel只使用Eloquent加入

提问于
浏览
2

在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() grab 所有团队,将其传递给我的视图,然后执行以下操作:

<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'));

谢谢,

1 回答

  • 3

    我认为Eager Loading会满足您的需求 . 就像是:

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

相关问题