這是我存盤在我的 API 控制器中的代碼:
return ApartmentResource::collection(Apartment::with(['sponsors'])->paginate(5));
它顯示了所有Apartments,有人的贊助商陣列為空,有人沒有。
我怎樣才能只顯示實際上有贊助商的公寓?
uj5u.com熱心網友回復:
您可以使用該has()方法
https://laravel.com/docs/9.x/eloquent-relationships#querying-relationship-existence
return ApartmentResource::collection(Apartment::has('sponsors')->with(['sponsors'])->paginate(5));
with()只需急切地加載贊助商:https ://laravel.com/docs/9.x/eloquent-relationships#eager-loading
uj5u.com熱心網友回復:
采用 array_filter()
例子:
$result = array_filter($array);
array_filter() 從陣列中洗掉空陣列元素。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/428459.html
上一篇:添加到購物車
