2015-04-20 303 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();