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记录数量:
- 接收者为当前用户的
shift值,或接收者为1; - 当前用户已在Pulicetxtrecive中生成关联记录,且该记录的
seen值为0(未读状态)。
问题代码
用户编写的无法正常工作的代码:
$pulictxtcount=Publictxt::where('reciver',Auth::user()->shift)->orwhere('reciver',1)->with('Publictxtrecives')->whereHas('Publictxtrecives',function($q){$q->where('seen', '=', 0);})->count();
问题分析与修复代码
原代码的核心问题有两个:
orWhere未被包裹在闭包中,导致查询逻辑变成「(接收者匹配当前用户shift) 或 (接收者为1且存在未读关联)」,不符合预期;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
相关产品推荐
相关产品推荐

