Brief
Sum parent category subcategories related products and add a custom column (e.g products_count
) to the parent category.
Migrations
Categories
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->unsignedBigInteger('category_id')->nullable();
$table->foreign('category_id')
->references('id')
->on('categories')
->onDelete('cascade');
$table->timestamps();
});
Products
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('price');
$table->timestamps();
});
Categorizables
Schema::create('categorizables', function (Blueprint $table) {
$table->id();
$table->integer('category_id');
$table->uuidMorphs('categorizable');
$table->timestamps();
});
Models
Category
public function subcategories()
{
return $this->hasMany(Category::class);
}
public function parent()
{
return $this->belongsTo(Category::class, 'category_id', 'id');
}
public function products()
{
return $this->morphedByMany(Product::class, 'categorizable');
}
Product
public function category()
{
return $this->morphToMany(Category::class, 'categorizable');
}
What I tried?
Category Model
public function getCountProductsAttribute()
{
if(!$this->category_id) {
$sum = 0;
collect($this->subcategories->loadCount('products'))->each(function($category) use(&$sum) {
$sum+=$category->products_count;
});
return $sum;
}
}
This will be count parent category subcategories products and return the sum to the category which is the parent category.
How to sum parent category subcategories products on the query process with eloquent without using mutators as me?