簡體   English   中英

如果關系數組為空,則不返回對象

[英]don't return the object if relation array is empty

更新

我有雄辯的對象

$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

您可以使用whereHas方法將“where”條件放在您的has查詢上,如下所示:

$storeCollections = StoreCollection::where('op_city_id', $opCity->id)
   ->where('isVisible', true)
   ->whereHas('storeCollectionStores')
    ...

這些方法允許您向關系約束添加自定義約束

這里閱讀文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM