首页 > 解决方案 > 如果关系数组为空,则不返回对象

问题描述

更新

我有雄辩的对象

$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": []
        },

标签: phplaraveleloquent

解决方案


您可以在外部集合上应用过滤器以检查内部 storeCollectionStores 集合是否具有元素。

$filteredCollection = $collection->filter(function($store) {
    return $store->storeCollectionStores->count() > 0;
});

您也可以在查询本身上 使用whereHas()与您类似的闭包。限制查询结果,加载相关数据。您需要同时使用过滤和加载。with()whereHaswith

https://laravel.com/docs/5.7/eloquent-relationships#querying-relationship-existence


推荐阅读