2016-01-22 34 views
4

docs當前hasManyThrough可以當U有類似country > users > posts如何在Laravel中使用'hasManyThrough'和超過3個表格?

這導致類似Country::whereName('xx')->posts; 這是偉大的,但如果我有比這更象

country > cities > users > posts 使用說明甚至

country > cities > towns > users > posts

怎麼會ÿ歐然後實現類似的東西,所以你可以寫在上面一樣

Country::whereName('xx')->posts;Town::whereName('xx')->posts;

回答

1

可悲的是,沒有一個簡單的解決方案,因此,繼承人什麼我發現

1添加其他表外ID進入郵遞表並堅持hasMany & belongsTo,ex。

posts 
    id - integer 
    country_id - foreign 
    // etc... 
    title - string 

2-與hasManyThrough走在每張桌子上除了user & post,因爲沒有必要,除非你想要去更深,恩。

countries 
    id - integer 
    name - string 

cities 
    id - integer 
    country_id - foreign 
    name - string 

towns 
    id - integer 
    city_id - foreign 
    name - string 

users 
    id - integer 
    town_id - foreign 
    name - string 

posts 
    id - integer 
    user_id - foreign 
    title - string 

- 所以咱們從第二個選項

1設置您的的hasMany & 屬於關聯關係如常

2-設置的hasManyThrough上嘗試模型。

3-實現Country::whereName('xx')->posts上面的例子中,我們添加的另一種方法的模型

// because Country::find($id)->towns, return an array 
// so to get all the posts we have to loop over that 
// and return a new array with all the country posts 
public function posts() 
{ 
    $posts = []; 

    foreach ($this->towns as $town) { 
     $posts[] = $town->posts; 
    } 

    return $posts; 
} 

4-作爲整個事情是努力通過foreign_id所以我們通過搜索ID而不是Country::find($id)->posts()

1

這是我所做的。我對@ ctfo的答案做了一些修改,所以它會作爲集合返回。

public function posts() 
{ 
    $posts = collect(); 

    foreach ($this->towns->get() as $town) { 
     $post = $town->posts(); 
     if ($post->count()) $posts = $posts->merge($post); 
    } 

    return $posts; 
} 

我希望這可以幫助任何經歷過的人。

相關問題