簡體   English   中英

Laravel 5.3從雄辯的關系中獲取自定義數組(對象)

[英]Laravel 5.3 get custom Array (Object) from Eloquent relationships

我有產品,屬性和類別。 我想創建自定義屬性數組而不使用foreach。 我知道我可以用foreach做到這一點,但是我想用口才的查詢來做到這一點。

這是我的表圖: 屬性表圖

我想這樣創建數組(Eloquent返回的對象):

$attributes = [
        'attribute1' => [
            'attribute1_property1' => 'attribute1_property1_count_in_all_products',
            'attribute1_property2' => 'attribute1_property2_count_in_all_products',
            'attribute1_property3' => 'attribute1_property3_count_in_all_products',
        ],
        'attribute2' => [
            'attribute2_property1' => 'attribute1_property1_count_in_all_products',
            'attribute2_property2' => 'attribute1_property2_count_in_all_products',
            'attribute2_property3' => 'attribute1_property3_count_in_all_products',
        ],
        ...
    ]

我有模型ProductAttributeAttributeProperty

Product::whereHas('categories', function ($q) use ($catId) {
        $q->whereId($catId);
    })->with('attributeProperties.attribute')->get();

通過上面的代碼,我可以獲得產品及其屬性選項的列表,但是我希望該屬性選項按父屬性分組,並計算有多少產品具有該屬性選項。

換句話說,我想所有attribute_options母公司分組attribute和計算多少產品做attribute_option有這樣的category 先感謝您。

您要查詢Product型號有任何特定原因嗎? 如果不需要這樣做,而您只是在示例數組之后,可以執行以下操作:

$results = Attribute::with(['attributeProperties' => function($query) {
    return $query->withCount('products');
}])->get();

您可以通過集合訪問想要的內容(我將每個項目的第一項僅供參考):

$attribute = $results->first();
$attributeProperty = $attribute->attributeProperties->first();
$attributeProperty->products_count;

或者,如果您需要精確格式的文件,則可以將結果映射為:

$results->keyBy('display_name')->map(function($attribute) {
    return $attribute->attributeProperties
        ->keyBy('display_name')
        ->map(function($property) {
            return $poperty->products_count;
        })
        ->toArray();
})
->toArray();

暫無
暫無

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

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