2017-02-21 90 views
0

我試圖實現一個博客類型的網站,用戶可以評價職位。因此,關係是這樣的:Laravel通過子表的關係

Blog -> blog_links; To Many fk = blog_id 
User -> blog_links; To Many fk = user_id 

我已經試過這些解決方案和每次得到一個不同的錯誤:

User::hasManyThrough(Blog::class, BlogLink::class); 

這並沒有工作,所以我想查詢範圍:

scopeWithLinksAndResorts($query) { 
    return $query->with(['resorts' => function($q) { 
     $q->ordered()->withLinks(); 
    }]); 
} 

也似乎並不返回任何結果。所以我不確定我在這裏做錯了什麼。而且這裏有一個表例如:

博客

id Title Text 
1  Test  This is a test blog 

用戶

id email 
1  [email protected] 

blog_links

id blog_id user_id rating 
1  1   1   4 
從這個我想獲得用戶評爲博客和他們的評級

現在。但正如我所說,我沒有得到任何結果。任何人都可以幫忙?

回答

0

在用戶模型在博客模型中定義博客的關係

/** 
* 
*/ 
public function blogs() 
{ 
    return $this->belongsToMany('App\Blog', 'blog_links', 'user_id', 'blog_id')->withPivot('rating'); 
} 

然後定義用戶的關係

/** 
* 
*/ 
public function users() 
{ 
    return $this->belongsToMany('App\User', 'blog_links','blog_id', 'user_id'); 
} 

要獲得他們的博客和評價的所有用戶,你可以做\App\User::with('blogs')->get()

我不確定這是你想要的,但希望它有幫助。

+0

非常感謝。沒有意識到你可以通過一個子表做一個belongsToMany,我認爲這是ManyThrough的目的?或者是在不同的情況下使用? – Byakku

+0

當你有多對多的關係必須有一個數據透視表和設置您的機型belongsToMany的關係,見(https://laravel.com/docs/5.4/eloquent-relationships#many-to-many)。 「」多對多「關係爲通過中間關係訪問遠程關係提供了便捷的途徑。」請參閱(https://laravel.com/docs/5.4/eloquent-relationships#has-many-through) – Nerea