如何在Laravel 8中获得一个关系数据的计数



我有一个Post, like和comment模型

我想在laravel中使用关系获取帖子数据,评论数据和喜欢的计数。

一切都在工作,但从下面的代码我得到喜欢数组,我想计数没有任何循环。这在关系式中可能吗?

这是我的PostController代码与关系:
$posts = Post::with('user','comment')->get();

Post模型:

public function comment(){
return $this->hasMany(Comment::class);
}
public function like(){
return $this->hasOne(Like::class);
}
像模型:

public function post(){
return $this->belongsTo(Post::class);
}

评论模型:

public function post(){
return $this->belongsTo(Post::class);
}

试试这个

$posts = Post::withCount('user')->withCount('comment')->get();

链接

用一个数组使用withCount()helper:

Post::withCount(['comment'])->get();

如果你想,你可以自定义你的计数:

Post::withCount([
'user',
'comment as comments_today_count' => function($query){
$query->where('created_at', '>', now()->subDays()
}])->get();

在hasMany关系中也应该使用复数:

public function comments(){
return $this->hasMany(Comment::class);
}

以便您可以更明确地使用它:

foreach($post->comments as $comment){...}

最新更新