php - 如果关系数组为空,则不返回对象
问题描述
更新
我有雄辩的对象
$storeCollections = StoreCollection::where('op_city_id', $opCity->id)
->where('isVisible', true)
->has('storeCollectionStores','>', 0)
->with([
'storeCollectionStores' => function ($query) use ($storeIds) {
$query->whereIn('store_id', $storeIds)->with(['store' => function ($query){
$query->select('id', 'ref', 'tagline', 'type', 'budget', 'cover', 'has_manager',
'timezone', 'priority', 'op_city_id', 'currency_id', 'ref_translation', 'tagline_translation')
->with([
'currency',
'storeTags.tag',
'labels' => function ($query) {
$query->select('id', 'label', 'store_id', 'label_translation');
},
]);
}])
->orderBy('priority', 'asc');
}
])
->orderBy('priority')
->get();
如果storeCollectionStore为空,我将得到空数组 。
如果关系为空,我想删除整个集合
有什么建议么?
结果是这样的
"storeCollections": [
{
"id": 9,
"title": "Our Favorites",
"desc": "Choose from our all-time favorite stores",
"priority": 0,
"isVisible": true,
"op_city_id": 1,
"created_at": "2018-11-08 11:11:18",
"updated_at": "2018-11-08 11:11:18",
"title_ar": "المفضلة لدينا",
"desc_ar": "اختر من بين جميع المتاجر المفضلة على",
"store_collection_stores": []
},
解决方案
您可以在外部集合上应用过滤器以检查内部 storeCollectionStores 集合是否具有元素。
$filteredCollection = $collection->filter(function($store) {
return $store->storeCollectionStores->count() > 0;
});
您也可以在查询本身上 使用whereHas()
与您类似的闭包。限制查询结果,加载相关数据。您需要同时使用过滤和加载。with()
whereHas
with
https://laravel.com/docs/5.7/eloquent-relationships#querying-relationship-existence
推荐阅读
- arrays - React:如何从一维数组制作二维数组?
- javascript - DropzoneJs - 上传完成后可以删除“删除链接”
- python - Python 帮助。在文件中查找最大值并打印出值 w 名称
- r - r - if (abs(x - oldx) < ftol) { 中的 mlogit 错误:需要 TRUE/FALSE 的缺失值
- php - 如何在 WordPress 中将汉堡菜单替换为默认菜单?
- encryption - Apache NiFi 写入加密的 SQS 队列
- c - 这个特定函数的时间复杂度 \big(O) 是多少?
- java - 如何在 Java 中并行运行 spark 程序
- c# - 在 localhost 上使用 asp.net core 2.1 身份时,TempData 丢失
- java - 我应该如何使用用户输入存储多维数组中的数组