【问题标题】:Laravel Eloquent Relationship issueLaravel Eloquent 关系问题
【发布时间】:2015-06-27 13:31:29
【问题描述】:

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

当我写作时

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

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

如何解决这个问题。

【问题讨论】:

  • 请发布错误
  • 旁注:你只需要做posts.comments 而不是两者都做,因为嵌套关系会加载它遍历的每个关系(posts & comments
  • 你的问题没有多大意义。您想要由某个用户创建但 user_id 在 cmets 表中的博客。博客的 cmets 的作者为何或如何规定博客本身属于谁?

标签: laravel eloquent


【解决方案1】:

你可以试试这个:

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

【讨论】:

    【解决方案2】:

    如果我理解正确,您想获取特定用户评论过的所有帖子。

    从您目前所做的来看,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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-28
      • 1970-01-01
      • 2015-07-05
      • 2016-09-20
      • 1970-01-01
      • 2021-06-19
      • 2014-05-24
      • 1970-01-01
      相关资源
      最近更新 更多