我有三个表,定义如下
用户
发布
评论
这是用户模型User.php
class User
{
public function post()
{
return $this->hasMany(Post::class);
}
}
这是我的帖子模型Post.php
class Post
{
public function comments()
{
return $this->hasMany(Comment::class);
}
}
问题:
我想使用雄辩的急切加载显示每位用户的评论数。
有人可以帮我吗?预先感谢。
您可以为用户的注释定义新的hasManyThrough
关系(docs):
class User
{
public function comments()
{
return $this->hasManyThrough(
'App\Comment',
'App\Post',
'user_id', // Foreign key on posts table...
'post_id', // Foreign key on comments table...
'id', // Local key on users table...
'id' // Local key on posts table...
);
}
}
现在您可以计算每个用户的评论(Laravel docs):
$users = App\User::withCount('comments')->get();
foreach ($users as $user) {
echo $user->comments_count;
}