试图通过其功能获得产品数量(多对多) 例如,
Product::with([’features’])->where(category_id, $category_id)->get();
产品A->功能1-> id
/ feature2-> id
/ feature3-> id
产品B->功能3-> id
/ feature4-> id
/ feature6-> id
.....
如何从每个功能中获取产品计数(按产品类别过滤)
我不擅长用语言解释,尽我所能。
最终结果 特色1-> 19产品 功能2-> 5产品 ...
答案 0 :(得分:0)
尝试一下:
Select product_id from products where category_id = "'.$category_id.'" group by feature_id;
答案 1 :(得分:0)
您应该在Product
和Feature
模型中定义关系
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
依次类推,等等
答案 2 :(得分:0)
假设您在products
模型上具有Feature
关系,可以尝试一下!
$features = Feature::withCount(['products' => function($query){
$query->where('category_id', $category_id);
}])->get();
对于集合的每个记录,您都会有一个products_count
。
答案 3 :(得分:0)
这可以解决问题
M[i,j] -> M[n+1-j,i] -> M[n+1-i,n+1-j] -> M[j,n+1-i] -> M[i,j]