【问题标题】:Laravel hasManyDeep issueLaravel 有很多深层问题
【发布时间】:2021-11-20 16:46:40
【问题描述】:

我已经实现了这种关系,其中一个仓库属于具有很多销售额的产品。

我的模特是这样的

仓库.php

public function products () {
    return $this->belongsToMany(Product::class)->withPivot('quantity');
}

product.php

public function sales () {
    return $this->hasMany(Sale::class);
}

我想直接从我的 Warehouse 模型中访问销售额,以对 sales 表中的一列求和。

我使用了 staudenmeir 的 GitHub 包,并在我的 Warehouse 模型中添加了一个 sales 方法。

public function sales () {
    return $this->hasManyDeep(Sale::class, ['product_warehouse', Product::class]);
}

我想要做的基本上是汇总销售表的总列,所以我在我的 WarehouseController 中添加了一个 withSum() 方法,如下所示

return Warehouse::query()
        ->withSum('sales', 'total')
        ->get();

结果

[
   {
      "id": 1,
      "warehouse": "Algeria",
      "sales_sum_total": "1000"
   },
   {
      "id": 2,
      "warehouse": "India",
      "sales_sum_total": "1000"
   }
]

这里的问题是,当我向印度仓库添加新销售时,它会为所有仓库返回相同的值。我认为我没有以正确的方式使用hasManyDeep() 方法,或者它可能不适用于我的用例。我能做些什么来让它发挥作用吗?

编辑: 我的数据库结构

    Schema::create('warehouses', function (Blueprint $table) {
        $table->id();
        $table->string('warehouse');
    });

    Schema::create('products', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->decimal('price');
    });

    Schema::create('product_warehouse', function (Blueprint $table) {
        $table->id();
        $table->foreignId('product_id')->constrained()->cascadeOnDelete();
        $table->foreignId('warehouse_id')->constrained()->cascadeOnDelete();
        $table->integer('quantity')->default(0);
    });

    Schema::create('sales', function (Blueprint $table) {
        $table->id();
        $table->foreignId('warehouse_id')->constrained()->cascadeOnDelete();
        $table->foreignId('product_id')->constrained()->cascadeOnDelete();
        $table->integer('quantity');
        $table->decimal('total');
    });

【问题讨论】:

    标签: laravel eloquent laravel-8


    【解决方案1】:

    虽然sales 表中有warehouse_id,但您可以将其作为简单的hasMany 关系处理并在其上调用sum, 我测试了你的案例并得到了正确的结果,我只是在仓库模型上添加了销售关系:

    public function sales()
    {
        return $this->hasMany(Sale::class);
    }
    

    我刚刚做到了:

    return Warehouse::withSum('sales', 'total')->get();
    

    【讨论】:

    • 这在我的情况下不起作用,因为我在 Warehouse 和 Product 模型之间有多对多的关系
    • 投反对票,不适合这种情况
    • 好的,我会编辑答案
    • @YasserSebai 我没有投反对票,我也不会。我很欣赏他的回答,即使它对我不起作用
    • 好的,感谢您的赞赏,感谢您让堆栈溢出成为更好的社区
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-10
    • 2011-06-21
    相关资源
    最近更新 更多