【问题标题】:Is this the correct Laravel 5 model relationship?这是正确的 Laravel 5 模型关系吗?
【发布时间】:2016-03-15 16:58:41
【问题描述】:

我有 3 个数据库表。

users
   id - integer
   username - string

post
   id - integer
   user_id - integer
   topic - string

comments
   id - integer
   user_id - integer
   post_id - integer

我在视图中所做的是循环浏览用户通过执行类似操作创建的所有帖子

Post::where('user_id', Auth::user()->id)->get();

在每个帖子中,其他用户可以对其发表评论。我想在帖子上显示一个计数,它唯一地计算有多少用户对该帖子发表了评论。我认为创建 hasManyThrough 关系在这里可以工作,但我继续为用户获得“0”计数。

用户模型:

class User extends Model {

public function post() 
{
   return $this->hasMany('App\Post')
}

public function comment()
{
   return $this->hasMany('App\Comment', 'user_id')
}

}

帖子模型:

class Post extends Model {

public function user()
{
   return $this->belongsTo('App\User')
}

public function comment()
{
   return $this->hasMany('App\Comment')
}

// I thought this method below would return the users who had commented on the post

public function commenters()
{
    return $this->hasManyThrough('App\User', 'App\Comment', 'user_id', 'username');
}

}

评论模型:

class Comment extends Model {

pubic function user()
{
  return $this->belongsTo('App\User')
}

public function post()
{
   return $this->belongsTo('App\Post')
}

}

所以最终结果应该是我猜的这样的结果?

查看:

<span>{{ $model->modelmethod->count() }}</span>

你们对此有何看法?这是正确的方法吗?或者你有什么不同的推荐吗?

【问题讨论】:

    标签: laravel orm laravel-5 eloquent


    【解决方案1】:

    为了解决您的第一个问题,我在视图中所做的是循环浏览用户通过执行类似操作创建的所有帖子,您可以使用 Eager Loading - 但是,这个将要求您访问嵌套元素。此查询检索用户及其所有帖子,包括评论者:

    $user = User::with('post.commenters')->where('id', $userId)->firstOrFail();
    

    这样您就可以使用$user-&gt;post 访问一系列用户的帖子。然后要访问它的评论者,您可以指定数组索引(或使用foreach loop)。即:

    //this is array access, accessing first post
    $user->post[0];
    //this iterate all post using foreach
    foreach($user->post as $posts){
      $post-> //do something with current post?
    }
    

    至于你的第二个麻烦,计数,它可以在数据库查询中完成 - 或在视图中(我经常在视图中这样做,因为它相当简单,可读且查询较少)。

    //this prints all posts number of commenters - in blade
    @foreach($user->post as $posts)
      @foreach($posts->commenter as $commenter)
        {{ count($commenter) }}
      @endforeach
    @endforeach
    

    编辑: 看起来我很想仔细阅读你的模型,它..无法完成

    return $this->hasManyThrough('App\User', 'App\Comment', 'user_id', 'username');
    

    应该是

    return $this->hasManyThrough('App\User', 'App\Comment', 'user_id', 'id');
    

    因为您实际上使用 user_id 而不是他们的用户名作为 cmets 中的外键。

    【讨论】:

    • 您好 tezla,我正在统计发表评论的用户数量。不是 cmets 的数量。
    • 啊,我的错,您可以通过急切加载获取用户 - 我将编辑我的答案。
    • 关键是在玩::with(relationship),如果您想检索发表评论者,请查看您的模型关系 - 可以通过它完成,但是不会检索实际评论。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-27
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 1970-01-01
    • 2011-10-02
    • 1970-01-01
    相关资源
    最近更新 更多