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

Laravel Eloquent中limit后count返回全量 如何统计最新1000条记录

你写的代码中count()方法执行时会重写查询语句为select count(*) as aggregate,会直接忽略前面设置的limit(1000)规则,所以返回的是符合where条件的全量数据行数,不会受limit限制。

以下是两种可直接落地的实现方案:

方案一:集合处理(推荐,性能最优)

只做1次数据库查询拿到最新1000条数据,后续在内存中做统计,1000条数据的计算开销可以忽略不计:

// 仅查询需要的activity字段,减少数据传输开销
$recent_activities = Activity::where('user_id', $user->id)
    ->latest('id')
    ->limit(1000)
    ->pluck('activity');

// 统计最新1000条总数量
$recent_count = $recent_activities->count();
// 统计各匹配条件的数量
$result_chat_refunds = $recent_activities->filter(fn($item) => str_starts_with($item, 'Credits erstattet'))->count();
$result_credit_membership = $recent_activities->filter(fn($item) => str_contains($item, 'Membership gutgeschrieben'))->count();
$result_credit_credits = $recent_activities->filter(fn($item) => str_contains($item, 'Credits gutgeschrieben'))->count();

如果你的PHP版本低于8.0不支持str_starts_with、str_contains方法,可以换成对应的原生字符串判断方法。

方案二:子查询实现(纯SQL统计)

如果不想把数据拉到应用层处理,可以通过子查询先圈定最新1000条的范围,再做条件统计:

// 构造子查询,获取对应用户最新1000条记录的id
$limitSubQuery = Activity::select('id')
    ->where('user_id', $user->id)
    ->latest('id')
    ->limit(1000);

// 统计总数量
$recent_count = Activity::whereIn('id', $limitSubQuery)->count();
// 统计各匹配条件的数量
$result_chat_refunds = Activity::whereIn('id', $limitSubQuery)
    ->where('activity', 'like', 'Credits erstattet%')
    ->count();
$result_credit_membership = Activity::whereIn('id', $limitSubQuery)
    ->where('activity', 'like', '%Membership gutgeschrieben%')
    ->count();
$result_credit_credits = Activity::whereIn('id', $limitSubQuery)
    ->where('activity', 'like', '%Credits gutgeschrieben%')
    ->count();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 15:33:03