2014-11-03 63 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