【问题标题】:Laravel - Many-to-many relation, product count by product featureLaravel - 多对多关系,按产品功能计算产品数量
【发布时间】:2019-03-23 05:49:39
【问题描述】:

试图通过其功能(多对多)获取产品数量 例如,

Product::with([’features’])->where(category_id, $category_id)->get();

产品 A->feature1->id

/feature2->id

/feature3->id

产品 B->feature3->id

/feature4->id

/feature6->id

.....

如何从每个功能中获取产品数量(按产品类别过滤后)

我不擅长用文字解释,我尽力了。

最终结果 功能 1 -> 19 个产品 功能 2 -> 5 个产品 ...

【问题讨论】:

    标签: php laravel eloquent many-to-many


    【解决方案1】:

    试试这个:

    Select product_id from products where category_id = "'.$category_id.'" group by feature_id;
    

    【讨论】:

    • 我怎样才能 groupBy feature->id?在产品集合中,每个产品可能有几个功能集合,所以 product->features->feature1->id, product->features->feature2->id, product->features->feature3->id
    • $product_features_with_count = Feature:: with(['products']) // ->where('products.category_id', $id) ->whereHas('products', function($q) use($id){ return $q->where('products.category_id', $id); }) ->find($feature_ids) ->groupBy('feature_type_id');
    • 我快到了,但不是集合不查询类别,它包括所有内容
    【解决方案2】:

    您应该在 ProductFeature 模型中定义关系

    class Product extends Model {
        public function features(){
            return $this->belongsTo(Feature::class);
        }
    }
    
    class Feature extends Model {
        public function products(){
            return $this->hasMany(Product::class);
        }
    }
    

    我假设每个Product 都有一个属性feature_id,其中包含它所属的Feature 的ID。

    $products = Product::with([’features’])->where(category_id, $category_id)->get(); // This query will return list of product
    
    foreach($products as $product){
        // You can access $feature of product like this
        $feature = $product->feature;
    }
    

    因为我已经定义了两个模型之间的反向关系,所以我也可以从 Feature 访问 Product。

    $feature->products(); // This will return a collection of Product and I can perform any sort of query on that too
    
    // Like count number of Products
    $feature->products()->count();
    $feature->products()->first(); // get the first product
    $feature->products()->last(); // get the last product
    

    以此类推,以此类推

    【讨论】:

    • 他们已经定义好了,我也有 productFeature 模型。产品集合已按类别和一些功能进行过滤,因此 productFeature 模型似乎无济于事
    【解决方案3】:

    假设您在Feature 模型上有products 关系,您可以试试这个!

    $features = Feature::withCount(['products' => function($query){
       $query->where('category_id', $category_id);
    }])->get();
    

    您将有一个 products_count 与集合的每条记录。

    【讨论】:

    • category_id 属于产品,不是来自功能,所以 where 子句不起作用
    【解决方案4】:

    这样就可以了

       with(['products' => function($q) use($category_id){
                        $q->where('category_id',18);
                    }])
    
                    ->find($feature_ids)
    
                    ->groupBy('feature_type_id');
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-18
    • 2014-09-13
    • 2015-01-28
    • 1970-01-01
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多