Laravel Eloquent在collection和count中都得到两次相同的关系



所以这个查询很漂亮:

Post::where('id', $id)
->with([
'comments' => function($query) {
$query->where('marked_as', 'active');
},
])
->withCount([
'comments as comments_active_count' => function ($q) {
$q->where('comments.marked_as', 'active');
},
'comments as comments_not_active_count' => function ($q) {
$q->where('comments.marked_as', 'not_active');
},
])
->firstOrFail();

但是除了单独获取计数之外,我还喜欢为每个状态单独获取评论集合,像这样(这不起作用):

Post::where('id', $id)
->with([
'comments as comments_active' => function($query) {
$query->where('marked_as', 'active');
},
'comments as comments_not_active' => function($query) {
$query->where('marked_as', 'not_active');
},
])
->withCount([
'comments as comments_active_count' => function ($q) {
$q->where('comments.marked_as', 'active');
},
'comments as comments_not_active_count' => function ($q) {
$q->where('comments.marked_as', 'not_active');
},
])
->firstOrFail();

这可能吗?

不能为with指定别名相反,您可以再创建2个关系

public function active_comments()
{
return $this->hasMany(Comment::class)->where('marked_as', 'active');
}
public function inactive_comments()
{
return $this->hasMany(Comment::class)->where('marked_as', 'not_active');
}

使用和

->with([ 'active_comments', 'inactive_comments' ])

->withCount([ 'active_comments', 'inactive_comments' ])

最新更新