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

Laravel项目提取特定用户统计数据异常,请求排查修复

问题排查:提取特定用户统计数据失败

问题描述

想要按来源提取特定用户的统计数据,但实际结果中所有来源行的用户统计数量完全一致,不符合预期。

相关代码

Model代码

public function getuser($user)
{
    $user = Client::where('user_id', $user)->where('created_at', '>=', '2022-07-01')->get();
    return $user;
}

Controller代码

$sources = Sources::get();

Blade代码

@foreach ($sources as $item)
    <tr>
        <td>{{$item->id}}</td>
        <td>{{$item->name}}</td>
        <td>{{$item->getuser(5)->count()}}</td>
        <td>{{$item->getuser(6)->count()}}</td>
        <td>{{$item->getuser(7)->count()}}</td>
    </tr>
@endforeach

效果对比

  • 预期效果:每行对应不同来源,展示该来源下用户5、6、7各自的统计数量(各行数值有差异)
  • 实际结果:所有来源行的用户统计数值完全相同,未按来源区分统计

问题修复方案

1. 核心问题定位

当前getuser方法直接全局查询Client表,没有关联当前Sources模型的记录,导致返回的是所有符合用户ID和时间条件的数据,而非对应来源下的专属数据。

2. 基础修复方案(关联来源过滤)

假设Client表存在source_id字段关联Sources表的id,修改Sources模型中的方法:

public function getUserCount($userId)
{
    // 通过关联关系,只统计当前来源下的指定用户数据
    return $this->hasMany(Client::class, 'source_id')
                ->where('user_id', $userId)
                ->where('created_at', '>=', '2022-07-01')
                ->count();
}

同时修改Blade模板调用:

@foreach ($sources as $item)
    <tr>
        <td>{{$item->id}}</td>
        <td>{{$item->name}}</td>
        <td>{{$item->getUserCount(5)}}</td>
        <td>{{$item->getUserCount(6)}}</td>
        <td>{{$item->getUserCount(7)}}</td>
    </tr>
@endforeach

3. 性能优化方案(避免N+1查询)

为减少数据库查询次数,在Controller中预加载统计数据:
首先在Sources模型定义关联:

public function clients()
{
    return $this->hasMany(Client::class, 'source_id');
}

然后修改Controller代码:

$sources = Sources::withCount([
    'clients as user_5_count' => function ($query) {
        $query->where('user_id', 5)->where('created_at', '>=', '2022-07-01');
    },
    'clients as user_6_count' => function ($query) {
        $query->where('user_id', 6)->where('created_at', '>=', '2022-07-01');
    },
    'clients as user_7_count' => function ($query) {
        $query->where('user_id', 7)->where('created_at', '>=', '2022-07-01');
    }
])->get();

最后Blade模板直接调用预加载的统计值:

@foreach ($sources as $item)
    <tr>
        <td>{{$item->id}}</td>
        <td>{{$item->name}}</td>
        <td>{{$item->user_5_count}}</td>
        <td>{{$item->user_6_count}}</td>
        <td>{{$item->user_7_count}}</td>
    </tr>
@endforeach

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 11:48:35