首页 文章

Laravel 5.3从Eloquent关系中获取自定义Array(Object)

提问于
浏览
0

我有产品,属性和类别 . 我想在不使用foreach的情况下创建自定义属性数组 . 我知道我可以用foreach完成它,但我想用Eloquent查询来做 .

这是我的表格图:
Attributes tables diagram

我想创建这样的数组(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 上有多少产品 . 先感谢您 .

1 回答

  • 1

    您查询 Product 型号有什么特别的原因吗?如果's not needed and you'刚好在示例数组之后,您可以这样做:

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

    您可以通过集合访问您想要的内容(我将每个项目的第一项仅供参考):

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

    OR 如果你需要那种EXACT格式,你可以映射结果如下:

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

相关问题