Laravel Eloquent 关系问题

Laravel Eloquent Relationship issue

我有三个模型 - 博客、Post、评论。 博客有很多Post Post 有很多评论

写的时候

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

它将为所有博客提供帖子和评论。 但是我将如何获得那些由管理员用户创建的博客,即评论 table 中的 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)

如何解决这个问题。

如果我没理解错的话,你想获取某个特定用户评论过的所有帖子。

根据您目前所做的,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

你可以试试这个:

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