与数据透视表Laravel的雄辩和内部循环的关系

时间:2014-05-01 18:10:15

标签: php laravel-4 eloquent

好的,任何人都可以帮我这个场景吗?我想使用Eloquent中的关系制作一个Divisions循环和该分部中所有团队的内循环。谷歌搜索和实验,但无法获得正确的结果。

我的表是这样的:

division_id INT PK
division_name VARCHAR
...

team_id INT PK
team_name VARCHAR
...

division_team(数据透视表)

id INT PK
division_id INT FK
team_id INT FK

我的模特是这样的: DivisionTeamPivot

class DivisionTeamPivot extends \Eloquent {
    protected $fillable = [];
    protected $table = 'division_team';

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

    public function division(){
        return $this->belongsTo('Division');
    }

Divisons

class Division extends \Eloquent {

    protected $primaryKey = 'division_id';
    public function teams(){
        return $this->hasMany('Team','division_team','division_id','team_id');
    }

}

class Team extends \Eloquent {

    protected $primaryKey  = 'team_id';
    public function division(){
        return $this->belongsTo('Division','division_team','team_id','division_id');
    }

}

我的控制器有:

$divisions = DivisionTeamPivot::with('Team','Division')->get();

我的观点:

<section class="panel">
            <header class="panel-heading">
               <h5>{{$division->division->division_name}} Division {{$i}}</h5>
            </header>
            <table class="table">
                <thead>
                <tr>
                    <th></th>
                    <th>Team Name</th>
                    <th class="center">Total Points</th>
                    <th class="center">Rank</th>
                </tr>
                </thead>
                <tbody>
                @foreach($division->team as $team)
                <tr>
                    <td width="75"><img src="/img/logos/{{team->team_logo}}" width="50"></td>
                    <td><a href="/teams/details"> {{team->team_name}}</a></td>
                    <td class="center">1,345</td>
                    <td class="center">1</td>
                </tr>
                 @foreach
                </tbody>
            </table>
        </section>

我想要做的是遍历各个部门,然后对这些部门中的团队进行子循环。我看到有人在这里制作一个数据透视表模型,但是当我使用它时,它会根据枢轴中的division_id表循环遍历所有相同的分区,但我得到了名称。它每个重复的部门创建一个团队。我需要根据他们所处的部门对他们进行分组。实际上,我仍然无法获得球队名称。我也非常希望热切的加载能够正常运行,因此我可以获得最有效的查询。谢谢!

1 个答案:

答案 0 :(得分:2)

要建立many-to-many关系,您需要在两个模型(belongsToManybelongsTo)中使用Division而不是Team,而不是需要为DivisionTeamPivot表使用另一个模型pivot。因此,在DivisionTeam中使用belongsToMany方法:

// Division Model
public function teams(){
    return $this->belongsToMany('Team', 'division_team', 'division_id', 'team_id');
}

// Team Model
public function divisions(){
    return $this->belongsToMany('Division', 'division_team', 'team_id', 'division_id');
}

进行如下查询:

$divisions = Division::with('teams')->get();
return View::make('viewname')->with('dvisions', $divisions);

view中,嵌套循环可能是这样的:

@foreach($divisions as $division)
    {{ $division->division_name }}
    @foreach($division->teams as $team)
        {{ ... }}
        {{ $team->team_name }}
    @endforeach
@endforeach