這個功能只有在 Laravel 8.12 以上才出現。讓你可以在使用Eloquent的關聯性資料表的時候,自動幫你加總、平均指定欄位得值或計算指定欄位的最大值。
我們一般會使用 withCount() 這個方法取得關聯性資料表中每一筆資料的對應總數。如下列例子,會列出comments這個關聯到post的資料表中單一post的comment數量。
$posts = Post::select(['title', 'body'])
->withCount('comments')
->get();
但是在 Laravel 8.12 以後,多了 withSum(), 等方法。
這一類方法有兩個參數需要帶入,除了本來的關聯資料表欄位之外,需要再填入一個要加總的欄位:withSum( 資料表, 要加總的欄位)
所產生的資料,會有一個 ‘主表_sum_欄位’ 的資料值出現。
use App\Models\Supporter;
$supporters = Supporter::withSum('goods', 'price')->get();
foreach ($supporters as $supporter) {
echo $supporter->supporter_sum_price;
}
同樣的,也可以使用withAvg(), withMin() 和withMax(),並且可以得對相對應的值。
$supporters = Supporter::withAvg('goods', 'price')->get();
// echo $supporter->supporter_avg_price;
$supporters = Supporter::withMin('goods', 'price')->get();
// echo $supporter->supporter_min_price;
$supporters = Supporter::withMax('goods', 'price')->get();
// echo $supporter->supporter_max_price;
附帶一提的是,這一系列的方法,背後所使用的query是 sub query的方式去取得所需的資料。所以,這樣的方式並不會對於效能產生什麼不好的影響,大家可以放心的使用。
這個功能是由Khalil Laleh在2020年10月25日提供。
相關連結如下:
https://laravel-news.com/laravel-8-13-0
https://github.com/laravel/framework/pull/34965
介紹的影片:
Recent Comments