[英]don't return the object if relation array is empty
UPDATED更新
I have eloquent object我有雄辩的对象
$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();
I'm getting empty array if storeCollectionStore is empty..如果storeCollectionStore为空,我将得到空数组。
I want to remove the whole collection if the relation is empty如果关系为空,我想删除整个集合
any suggestions?有什么建议?
result is like this结果是这样的
"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": []
},
You can either apply a filter on the outer collection to check if the inner storeCollectionStores collection has elements.您可以在外部集合上应用过滤器以检查内部 storeCollectionStores 集合是否包含元素。
$filteredCollection = $collection->filter(function($store) {
return $store->storeCollectionStores->count() > 0;
});
You could also just use whereHas()
with a similar closure to your with()
on the query itself.您也可以在查询本身上使用whereHas()
与您的with()
类似的闭包。 whereHas
limits the query results, with
loads the related data. whereHas
限制了查询结果, with
负载相关的数据。 You need to use both to filter and load.您需要同时使用两者来过滤和加载。
https://laravel.com/docs/5.7/eloquent-relationships#querying-relationship-existence https://laravel.com/docs/5.7/eloquent-relationships#querying-relationship-existence
you could use whereHas
method to put "where" conditions on your has
queries like this:您可以使用whereHas
方法将“where”条件放在您的has
查询上,如下所示:
$storeCollections = StoreCollection::where('op_city_id', $opCity->id)
->where('isVisible', true)
->whereHas('storeCollectionStores')
...
These methods allow you to add customized constraints to a relationship constraint这些方法允许您向关系约束添加自定义约束
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.