简体   繁体   中英

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..

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.

$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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM