You need to enable JavaScript to run this app. Laravel使用withAvg时如何排除软删除记录使无有效数据返回null
优惠活动
大模型
产品
解决方案
定价
更多

Laravel使用withAvg时如何排除软删除记录使无有效数据返回null

问题原因

你遇到的问题本质是withAvg会默认沿用你定义的posts关联的查询条件,如果你的posts关联配置了包含软删除记录(比如加了withTrashed(),这也能解释为什么你with('posts')能返回已软删除的记录),计算平均值时就会把软删除的Post也纳入统计,所以全部软删时也会返回计算值而非null。

解决方案

方案1:临时给withAvg加软删除过滤(单次使用)

直接在withAvg的关联参数中传入闭包,排除软删除记录即可,代码修改如下:

User::whereId(2)
    ->with('posts')
    ->withAvg(['posts AS post_avg' => function ($query) {
        // 统计时仅包含未软删除的Post
        $query->whereNull('deleted_at');
    }], 'counts')
    ->first();

PHP 7.4及以上版本可以用箭头函数简化:

User::whereId(2)
    ->with('posts')
    ->withAvg(['posts AS post_avg' => fn($q) => $q->whereNull('deleted_at')], 'counts')
    ->first();

方案2:单独定义排除软删除的关联(多次复用)

如果你有多处需要统计未软删除Post的聚合值,可以直接在User模型中单独定义一个不含软删除的关联:

// App\Models\User.php
public function validPosts()
{
    // 此处按你的实际关联关系调整,hasMany还是hasOne等
    return $this->hasMany(Post::class)->whereNull('deleted_at');
}

调用时直接用新关联即可,代码更简洁:

User::whereId(2)
    ->with('posts')
    ->withAvg('validPosts AS post_avg', 'counts')
    ->first();

两种方案都可以实现:所有Post都软删除时,post_avg字段返回null的预期效果。

内容的提问来源于stack exchange,提问作者schutte

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 09:39:01