You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中如何用withSum/withCount统计Auth::user关联产品总价

Laravel 多层关联模型的Price总和统计实现

关联关系回顾

确保你的模型已正确定义关联:

  • User模型:
public function categories()
{
    return $this->hasMany(Category::class);
}
  • Category模型:
public function posts()
{
    return $this->hasMany(Post::class);
}
  • Post模型:
public function product()
{
    return $this->hasOne(Product::class);
}

方法一:使用withSum嵌套关联统计

Laravel支持通过点语法直接指定多层嵌套关联,用withSum统计目标字段总和:

// 加载用户及所有关联Product的price总和
$user = Auth::user()->withSum('categories.posts.product', 'price')->first();

// 访问计算出的总和
$totalPrice = $user->categories_posts_product_sum;

如果需要过滤数据(比如排除空价格的Product),可以通过闭包自定义查询:

$user = Auth::user()->withSum(
    ['categories.posts.product' => function ($query) {
        $query->whereNotNull('price'); // 过滤price为空的记录
    }],
    'categories.posts.product.price'
)->first();

方法二:直接通过查询构造器统计

如果只需要总和而不需要加载用户模型的其他数据,直接用查询构造器更高效:

$totalPrice = Product::whereHas('post.category', function ($query) {
    $query->where('user_id', Auth::id());
})->sum('price');

说明

  • withSum会将统计结果作为附加属性挂载到User模型实例上,属性名规则为[关联路径]_sum(比如示例中的categories_posts_product_sum)。
  • 直接查询的方式跳过了用户模型的加载,适合仅需获取总和的场景,性能更优。

内容的提问来源于stack exchange,提问作者Rajib Bin Alam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 09:02:58