2015-04-20 301 views
0

我有三種模式 - 博客,發佈,評論。 博客有很多帖子 張貼有許多評論Laravel雄辯關係問題

當我寫

return Blog::with('posts','posts.comments')->get(); 

它會給所有文章和評論的博客。 但是,我將如何獲取由admin用戶創建的博客,即註釋表中的user_id。在哪寫->where條件。

return Blog::with('posts','posts.comments')->where('comments.user_id','=','23')->get(); 

給出錯誤。

SQLSTATE[42P01]: Undefined table: 7 ERROR: missing FROM-clause entry for table "comments" 
LINE 1: select * from "blogs" where "comments"."is_... 
^ (SQL: select * from "blogs" where "comments"."user_id" = 23) 

如何解決此問題。

+1

請張貼錯誤 – user1012181

+1

旁註:你只需要做'posts.comments'而不是兩個,因爲嵌套關係將加載它迭代的每個關係('posts'&'comments') – SamV

+0

你的問題沒有多大意義。您想要由某個用戶創建的博客,但user_id位於評論表中。博客評論的作者爲什麼或者如何決定博客本身屬於誰? – user3158900

回答

1

如果我理解正確,您將獲得已由特定用戶發表評論的所有帖子。

從你迄今爲止所做的,whereHas()可能是你在找什麼。這是你如何做到的。

return Blog::with('posts.comments') 
       ->whereHas('posts.comments', function($q) use ($user){ 
        $q->where('comments.user_id', $user->id); 
       })->get(); 

來源:http://laravel.com/docs/5.0/eloquent#querying-relations

+0

工程。謝謝 :-) –

0

你可以試試這個:

return Blog::with([ 'posts', 'posts.comments' => function($query) 
{ 
    $query->where('comments.user_id', '23'); 
}])->get();