如何获取具有parent_id的子类别中所有项目的计数和值。我有一个与产品模型有关的类别模型。在类别表中,有parent_id及其子类别。如何退回属于父类别的所有产品?
数据库如下所示 Database
关系显示在这里
public function products()
{
return $this->hasMany('App\Product');
}
public function category()
{
return $this->belongsTo('App\Category');
}
然后在我的控制器中,这将返回0作为计数
public function niche($url)
{
$niche = Category::where('url',$url)->first();
$categories = Category::where('parent_id',$niche->id)->get();
$products = [];
foreach($categories as $category) {
$products = Product::where('category_id',$category->id)->get();
}
dd($products->count());
}
请问我如何获得属于该细分市场的产品数量? 谢谢。
答案 0 :(得分:0)
我认为products()
是产品和类别的关联方法
您可以这样尝试吗?
$products = [];
foreach($categories as $category){
array_push($products, $category->products());
}
dd(count($products, true));
答案 1 :(得分:0)
我认为这是因为每次循环时都会创建一个新的产品变量,因此它总是会倾倒循环中最后一个类别的计数。
您应该尝试这样的事情:
public function niche($url){
$niche = Category::where('url',$url)->first();
$categories = Category::where('parent_id',$niche->id)->get();
$products = [];
foreach($categories as $category){
array_push($products,$category->products());
}
dd($products->count());
}
答案 2 :(得分:0)
我认为结果为0,可能是因为最后一个子类别没有任何乘积。
顺便说一句,我建议在此基础上使用一种更清洁的方法。让我们为类别定义子类别关系。
class Category extends Model
{
public function products()
{
return $this->hasMany('App\Product');
}
public function subCategories()
{
return $this->hasMany(static::class, 'parent_id');
}
}
因此,您可以通过多种方式访问产品和产品数量:
// You can eager load for performance.
$category = Category::with('subCategories.products')->where('url', $url)->first();
$products = $category->subCategories->flatMap->products;
$count = $products->count();
// Or you can eager load JUST the number of products.
$category = Category::withCount('subCategories.products')->where('url', $url)->first();
$numberOfProducts = $category->products_count;
答案 3 :(得分:0)
你必须在子关系上使用 withCount。
$categories = Category::whereNULL('parent_id')->with(['categories' => function ($query) {
$query->withCount('products');
}])->get();
希望应该可以工作