Laravel 通过另一张表雄辩关系

RMK*_*147 1 orm laravel eloquent laravel-4 laravel-5

我有以下数据库表:

季节

  • ID
  • 数字

团队

  • ID
  • 姓名

积分榜

  • ID
  • season_id
  • 团队 ID

问题是,我怎样才能让一个赛季的所有球队都进入积分榜。目前我对所有团队都是这样的:

$teams = [];

$standings = $season->standings;

foreach($standings as $standing){

     $teams[] = $standing->team;

}
Run Code Online (Sandbox Code Playgroud)

有没有办法使用 Eloquent 关系来做到这一点?我尝试过 HasManyThrough 但没有成功。这些是我的模型目前的样子:

class Season extends Eloquent{

    public function standings(){

        return $this->hasMany('Standing');

    }

}

class Standing extends Eloquent{

    public function team(){

        return $this->belongsTo('Team');

    }

}

class Team extends Eloquent{

    public function standings(){

        return $this->belongsToMany('Standing');

    }

}
Run Code Online (Sandbox Code Playgroud)

use*_*496 5

你们的人际关系看起来有点不对劲。以下是您应该需要的所有关系,尽管只belongsToMany需要查找一个赛季中所有球队的特定场景所需的关系。

class Season extends Eloquent {

    public function teams()
    {
        return $this->belongsToMany('Team', 'Standings');
    }

    public function standings()
    {
        return $this->hasMany('Standing');
    }
}

class Team extends Eloquent {

    public function seasons()
    {
        return $this->belongsToMany('Season', 'Standings');
    }

    public function standings()
    {
        return $this->hasMany('Standing');
    }
}

class Standing extends Eloquent {

    public function team()
    {
        return $this->belongsTo('Team');
    }

    public function season()
    {
        return $this->belongsTo('Season');
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以使用belongsToMany关系而不是 ahasManyThrough来查询一个赛季中的所有球队。那看起来像......

Season::with('teams')->find($season_id);

foreach($season->teams as $team) {
    echo $team->name;
}
Run Code Online (Sandbox Code Playgroud)