Laravel 8 關聯(lián)模型計數(shù)

2021-07-19 11:40 更新

如果想要只計算關聯(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; 

如果將 withCountselect 查詢組裝在一起,請確保在 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);
}]) 
以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號