2014-11-03 101 views
0

我有3個機型:Persons,EventsFiles。 A Persons可以有許多Events,許多Events可以有許多FilesHasMany with belongsToMany relationship

| persons | 
----------- 
id 
name 


| events | 
---------- 
id 
person_id 
name 


| event_file | 
-------------- 
id 
event_id 
file_id 


| files | 
--------- 
id 
name 

Persons模式,我有這樣的關係:

public function events() 
{ 
    return $this->hasMany('Events', 'person_id'); 
} 

Events模式:

public function files() 
{ 
    return $this->belongsToMany('Files', 'event_file', 'event_id', 'file_id'); 
} 

是否有可能直接PersonsFiles這相當於之間建立的關係例如:

$files = Person::find($id)->events->files; 
// OR 
$files = Person::find($id)->files; 

謝謝!

+0

不,內建方法不可行。 – 2014-11-03 16:51:24

回答

0

像在評論中一樣,不可能建立這樣的關係運用內在的雄辯方法。下面是如何使用有點掛羊頭賣狗肉的獲得files:在上面的例子

$files; // collection of files related to the Person through collection of his events 

記住,這個代碼將運行額外的查詢來獲取文件,因此:

Person::with(['events.files' => function ($q) use (&$files) { 
    $files = $q->get()->unique(); 
}])->find($id); 

然後

1 fetch Person 
2 fetch Events related to Person 
3 fetch Files related to all the Events 
4 again fetch Files related to all the Events 
+0

謝謝你的回答。它完美的工作! – 2014-11-04 09:02:31

0

您可以使用「hasManyThrough」。 在下面的示例中,您可以看到我想通過用戶獲取帖子。就像你想通過事件獲取文件一樣。

class Country extends Eloquent { 

    public function posts() 
    { 
     return $this->hasManyThrough('Post', 'User'); 
    } 

} 

你將調用爲:

$country->posts; 

或者,如你所願:

Person:find(1)->files; 

如果你想有一個更好的解釋,按照鏈接到Laravel自己的頁面: http://laravel.com/docs/4.2/eloquent#has-many-through

+0

不,'hasManyThrough'不能與'belongsToMany'一起使用。 – 2014-11-03 16:50:38

+0

我不明白你的意思。它不是「與」,它正在取代。有這樣的問題使用?我現在無法測試它。 – klauskpm 2014-11-03 16:57:33

+0

是的,它不會與級聯以外的關係一起工作,即。 'A hasMany B,B hasMany C'。我根本不是在說'用'方法。 – 2014-11-03 17:05:11

0

什麼

Person::where('id',$id)->with('events')->with('events.files')->get(); 

?急於加載

+0

謝謝你的回答。它也完美地工作! – 2014-11-04 09:03:37