Laravel使用三个键进行多对多查询


Laravel many-to-many query with three keys?

我很难完全理解laravels关系系统。我想了解在某个音乐节的某个乐队中演奏的各种各样的人。

这是我的桌子:

带状结构表:

id, festival_id, band_id, person_id

人员表:

id, firstname, lastname

节日餐桌:

id, festivalname

波段表:

id, bandname

在我的节日模型中,我有这个:

    public function persons() {
    return $this->belongsToMany('Person','fs_festival_persons','festival_id','person_id');
}

要列出节日中的所有人,我在控制器中使用以下代码:

$persons = $festival->persons()->get();

而且效果很好。(从个人节日数据透视表中检索)。但我不确定如何使用一些laravel魔法来制作一个从Bandstructure派生的人的列表,在这里,当我有festival_id和band_id时,我会检索所有的person_id,并将其制作成一个person数组。有什么想法吗?我试了很多次,在谷歌上搜索了一下,但都找不到适合我的例子。

也许你可以试试wherePivot()这样的雄辩函数:

在您的Bandstruckture模型中:

<?php
class Bandstruckture extends Eloquent {
    public function persons()
    {
        return $this->belongsToMany('Person')->withPivot(['festival_id', 'band_id']);
    }
}

像这样使用:

$persons = $festival->persons()->wherePivot('festival_id', $festival_id)->wherePivot('band_id', $band_id)->get();