W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
如果想要只計算關聯(lián)結果的統(tǒng)計數(shù)量而不需要真實加載它們,可以使用 withCount
方法,它將放在結果模型的 {relation}_count
列。示例如下:
$posts = App\Models\Post::withCount('comments')->get();
foreach ($posts as $post) {
echo $post->comments_count;
}
可以像給查詢添加限制一樣為多個關系添加「計數(shù)」:
use Illuminate\Database\Eloquent\Builder;
$posts = App\Models\Post::withCount(['votes', 'comments' => function (Builder $query) {
$query->where('content', 'like', 'foo%');
}])->get();
echo $posts[0]->votes_count;
echo $posts[0]->comments_count;
還可以給關聯(lián)計數(shù)結果起別名,這允許你在同一關聯(lián)上添加多個計數(shù):
use Illuminate\Database\Eloquent\Builder;
$posts = App\Models\Post::withCount([
'comments',
'comments as pending_comments_count' => function (Builder $query) {
$query->where('approved', false);
},
])->get();
echo $posts[0]->comments_count;
echo $posts[0]->pending_comments_count;
如果將 withCount
和 select
查詢組裝在一起,請確保在 select
方法之后調用 withCount
:
$posts = App\Models\Post::select(['title', 'body'])->withCount('comments')->get();
echo $posts[0]->title;
echo $posts[0]->body;
echo $posts[0]->comments_count;
此外,使用 loadCount
方法,您可以在父模型被加載后使用關聯(lián)計數(shù):
$book = App\Models\Book::first();
$book->loadCount('genres');
如果您需要在預加載查詢上設置額外的查詢約束,您可以傳遞一個希望加載的關聯(lián)數(shù)組。數(shù)組值應該是 Closure
實例,它接收查詢生成器實例:
$book->loadCount(['reviews' => function ($query) {
$query->where('rating', 5);
}])
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: