Reputation: 604
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..
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": []
},
Upvotes: 1
Views: 1771
Reputation: 2164
you could use whereHas
method to put "where" conditions on your has
queries like this:
$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
Read the docs here
Upvotes: 0
Reputation: 35367
You can either apply a filter on the outer collection to check if the inner storeCollectionStores collection has elements.
$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
limits the query results, with
loads the related data. You need to use both to filter and load.
https://laravel.com/docs/5.7/eloquent-relationships#querying-relationship-existence
Upvotes: 1