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

Laravel关联模型数据获取问题:Publictxt与Pulicetxtrecive查询失效

问题:统计关联Pulicetxtrecive的Publictxt未读记录数量

模型定义

Publictxt 模型

class Publictxt extends Model
{
    protected $fillable=['sender','reciver','description','useridseen'];

    public function Publictxtrecives()
    {
        return $this->hasMany(Pulicetxtrecive::class,'publictxt_id', 'id');
    }
}

Pulicetxtrecive 模型

class Pulicetxtrecive extends Model
{
    protected $fillable=['publictxt_id','user_id','seen'];

    public function publictxts()
    {
        return $this->belongsTo(Publictxt::class);
    }
}

需求说明

需要统计满足以下条件的Publictxt记录数量:

  1. 接收者为当前用户的shift值,或接收者为1;
  2. 当前用户已在Pulicetxtrecive中生成关联记录,且该记录的seen值为0(未读状态)。

问题代码

用户编写的无法正常工作的代码:

$pulictxtcount=Publictxt::where('reciver',Auth::user()->shift)->orwhere('reciver',1)->with('Publictxtrecives')->whereHas('Publictxtrecives',function($q){$q->where('seen', '=', 0);})->count();

问题分析与修复代码

原代码的核心问题有两个:

  1. orWhere未被包裹在闭包中,导致查询逻辑变成「(接收者匹配当前用户shift) 或 (接收者为1且存在未读关联)」,不符合预期;
  2. whereHas中未筛选当前用户的关联记录,会统计所有用户的未读数据,而非当前用户。

修复后的代码:

$pulictxtcount = Publictxt::where(function ($query) {
        // 把两个接收者条件包裹在闭包内,确保是一组逻辑
        $query->where('reciver', Auth::user()->shift)
              ->orWhere('reciver', 1);
    })
    ->whereHas('Publictxtrecives', function ($q) {
        // 限定当前用户的未读关联记录
        $q->where('user_id', Auth::user()->id)
          ->where('seen', 0);
    })
    ->count();

额外优化提示

如果不需要在后续逻辑中使用Publictxtrecives关联数据,可以去掉with('Publictxtrecives')——whereHas仅用于判断关联记录是否存在,不会加载关联数据,去掉后能降低查询开销。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 17:10:20