Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 views
in Technique[技术] by (71.8m points)

laravel - How to get a total amount of products in children categories of single parent

I have a Category model in which has children categories which has products... getting the total amount of products along with the children is easy. But what about getting the parent categories total amount which is the sum of all children categories of this single parent?

Here is the AppCategory model:

public function products()
{
    return $this->hasMany(Product::class, 'category_id');
}

public function parent()
{
    return $this->hasOne(Category::class, 'id', 'parent_id');
}

public function children()
{
    return $this->hasMany(Category::class, 'parent_id', 'id');
}

public function scopeTotalShirts($query)
{
    return $query->where('slug', 'shirts')->first()->children->each->products()->count();
}

A shirt would have child categories such as T-Shirt, Long Sleeve, Graphic, etc.

I want to get the total of those children categories so it all adds up in the Shirts (parent) category.

Is there some elegant way to do this besides querying up the children categories and getting the count?

Thank you!

question from:https://stackoverflow.com/questions/65867204/how-to-get-a-total-amount-of-products-in-children-categories-of-single-parent

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Based on your answer you can remove the extra queries in the loop, at the least:

$children = $category->children()->withCount('products')->get();

return $children->sum('products_count');

Or you can do the actual query from the inverse direction and remove the need for all of this:

return Product::whereHas('child.category', function ($q) {
    $q->where('slug', 'shirts');
})->count();

Though, I don't know how you setup these relationships in the inverse.


Based on the relationships you have you probably need to do more querying here as I would suppose a Product could belong to a parent or child category:

return Product::whereHas('category', function ($q) {
    $q->where('slug', 'shirts')
        ->orWhereHas('parent', fn ($q) => $q->where('slug', 'shirts'));
})->count();

The Product model should have a category relationship (belongsTo). The parent relationship on Category should be a belongsTo not hasOne.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...