因此,這個查詢的效果很好:
Post::where('id'/span>, $id)
->with([
'comments' => function($query) /span>{
$query->where('marked_as', 'active') 。
},
])
->withCount([
'comments as comments_active_count' => function ($q) /span>{
$q->where('comments.marked_as', 'active') 。
},
'comments as comments_not_active_count' => function ($q) /span>{
$q->where('comments.marked_as', 'not_active') 。
},
])
->firstOrFail()。
但是,除了單獨獲得計數,我還想為每個狀態單獨獲得評論集合,就像這樣(這不起作用):
Post::where('id'/span>, $id)
->with([
'comments as comments_active' => function($query) {
$query->where('marked_as', 'active') 。
},
'comments as comments_not_active' => function($query) /span>{
$query->where('marked_as', 'not_active') 。
},
])
->withCount([
'comments as comments_active_count' => function ($q) /span>{
$q->where('comments.marked_as', 'active') 。
},
'comments as comments_not_active_count' => function ($q) /span>{
$q->where('comments.marked_as', 'not_active') 。
},
])
->firstOrFail()。
這可能嗎?
uj5u.com熱心網友回復:
你不能給與一個別名。 相反,你可以再創建2個關系
public function active_comments()
{
return $this->hasMany(Comment::class)->where('marked_as'/span>, 'active'/span>) 。
}
public function inactive_comments()
{
return $this->hasMany(Comment::class)->where('marked_as'/span>, 'not_active'/span>) 。
}
并使用
->with([ 'active_comments', 'inactive_comments' ] )
而且
->withCount([ 'active_comments', 'inactive_comments' ] )
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/332460.html
標籤:
