Laravel eloquent 多对多并且有很多关系

Laravel eloquent many to many and has many relationships

我有这个Warehouse → many to many → Product → has many → Sale

我的人际关系

warehouse.php

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

product.php

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

我想获取每个仓库的销售额

我试过的

return Warehouse::with('products.sales')->get();

意外结果

{
    "id": 1,
    "warehouse": "India",
    "products": [
        {
            "id": 19,
            "name": "Taylor Lester",
            "price": "745.00",
            "sales": [
                {
                    "id": 1,
                    "warehouse_id": 1,
                    "product_id": 19,
                    "user_id": 1,
                    "quantity": 20
                },
                {
                    "id": 2,
                    "warehouse_id": 1,
                    "product_id": 19,
                    "user_id": 1,
                    "quantity": 30
                }
            ]
        }
    ]
},
{
    "id": 2,
    "warehouse": "Malaysia",
    "products": [
        {
            "id": 19,
            "name": "Taylor Lester",
            "price": "745.00",
            "sales": [
                {
                    "id": 1,
                    "warehouse_id": 1,
                    "product_id": 19,
                    "user_id": 1,
                    "quantity": 20
                },
                {
                    "id": 2,
                    "warehouse_id": 1,
                    "product_id": 19,
                    "user_id": 1,
                    "quantity": 30
                }
            ]
        }
    ]
}

我想要的是每个仓库的销售额。比如印度仓库只有2个sales 而马来西亚仓库只有1个sale

我该如何实施这种方法?

在laravel中使用withCount只计算相关模型

return Warehouse::with('products' => function($query){
    $query->withCount('sales');
})->get();

根据数据,您的 Sale 模型有一个 warehouse_id 列。为什么这种关系不在您的 Warehouse 模型中?

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

然后

return Warehouse::with('sales')->get();