1

简短的

汇总父类别子类别相关产品并将自定义列(例如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?

4

1 回答 1

1

好的,基于子类别可以有子类别的要求,我们需要一个递归解决方案。您可以执行以下操作:

public function getCountProductsAttribute()
{
    if (! $this->relationLoaded('subcategories.products') {
        $this->load('subcategories.products');
    }
    
    if ($this->subcategories->isEmpty()) {
        return $this->products->count();
    }

    return $this->subcategories->reduce(function ($sum, $sub) {
        $sum += $sub->countProducts;
        return $sum;
    }, $this->products->count());
}

现在要在查询结果中添加“products_count”,我们可以在运行时附加它,如下所示:

    $category = Category::find($id)->append('countProducts');

附加当然只会在结果被序列化(即 toArray 或 toJson)时出现。

于 2020-07-18T09:37:09.090 回答