简短的
汇总父类别子类别相关产品并将自定义列(例如products_count
)添加到父类别。
迁移
类别
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();
});
产品
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('price');
$table->timestamps();
});
分类
Schema::create('categorizables', function (Blueprint $table) {
$table->id();
$table->integer('category_id');
$table->uuidMorphs('categorizable');
$table->timestamps();
});
楷模
类别
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');
}
产品
public function category()
{
return $this->morphToMany(Category::class, 'categorizable');
}
我试过什么?
类别模型
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;
}
}
这将计算父类别子类别产品并将总和返回到作为父类别的类别。
如何使用 eloquent 对查询过程中的父类别子类别产品求和,而不像我一样使用 mutators?