Laravel 7 API 仅显示包含关系的数据的资源

Laravel 7 API Resource showing only data that contains relationship

我的代码存储在我的 API 控制器中:

return ApartmentResource::collection(Apartment::with(['sponsors'])->paginate(5));

它显示了所有 Apartments,有些赞助商数组为空,有些则没有。

如何只显示实际有赞助商的公寓?

使用 array_filter()

示例:

$result = array_filter($array);

array_filter() 从数组中删除空数组元素。

可以使用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