我有一个user->hasMany-> posts->hasMany ->comments
关系。
我想在昨天留下评论的不同帖子中获取所有用户评论并计算评论。
到目前为止我在做什么:
$user = User::where("id", $id)->with("comments")->where(["comments"=>function ($a){
return $a->where("created_At", DB::Raw("YESTERDAY(created_at)"))
}])->get();
但它返回了我所有的评论。
答案 0 :(得分:0)
如果您要加载所有帖子中包含计数评论的用户,请使用withCount()
:
User::withCount(['postsComments' => function($q) {
return $q->whereDate('created_at', Carbon::yesterday());
}])
->find($id);
要使其有效,请定义新的hasManyThrough
关系:
public function postsComments()
{
return $this->hasManyThrough(Comment::class, Post::class);
}
答案 1 :(得分:0)
应该是:
$posts = Post::where("user_id", $id)->with(["comments"=> function ($query){
$query->where("comments.created_at", Carbon::yesterday());
})->get();
$countComments = $posts->sum(function($query){
return $query->comments->count();
});
$countComments
现在应该提供昨天用户评论的数量。
答案 2 :(得分:0)
<强>尝试:强>
$yesterday = date("Y-m-d", strtotime( '-1 days' ) );
$user = User::where("id", $id)->with("comments")->where(["comments"=>function ($a) use ($yesterday) {
return $a->whereDate('created_at', $yesterday )
}])->get();