2015-02-11 44 views
0

我很难完全理解laravels关系系统。我想获得某个节日中某个乐队演奏的人物变量。Laravel带三个键的多对多查询?

这里是我的表:

Bandstruckture表:

id, festival_id, band_id, person_id 

Person表:

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,并将其制作为人物阵列。有任何想法吗?我已经尝试了很多,并且搜索到了,但是找不到任何适合我的例子。

+0

我可以手动做一个这样的查询: $ persons = DB :: table('fs_persons') - > join('fs_bandstruktur' ,'person_id','=','fs_persons.id') - > where('band_id','=',$ band_id) - > get(); 得到我想要的结果,但希望有一些laravel魔术 – 2015-02-11 01:36:11

+0

你尝试了雄辩的方法“wherePivot()”? – 2015-02-11 02:25:39

回答

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