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

时间:2015-02-11 00:38:42

标签: php laravel relationship

我无法完全理解laravels关系系统。我想得到一个在某个节日中在某个乐队中演奏的人的变量。

以下是我的表格:

Bandstruckture表:

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派生的人员列表,在那里我检索所有person_id,当我有festival_id和band_id,并使其成为一个人阵列。有任何想法吗?我已经尝试了很多,谷歌搜索,但无法找到任何适合我的例子。

1 个答案:

答案 0 :(得分:0)

也许您可以尝试 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();