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



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

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

它显示所有Apartments,有人的赞助商数组为空,有人没有。

我怎么能只展示那些有赞助商的公寓?

您可以使用has()方法

https://laravel.com/docs/9.x/eloquent-relationships#querying-关系存在

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

with()只是急于加载赞助商:https://laravel.com/docs/9.x/eloquent-relationships#eager-加载

使用array_filter()

示例:

$result = array_filter($array);

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

最新更新