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

Laravel按日期过滤关联表统计行数 统计offer关联report表行数并倒序

Laravel关联统计实现方案

首先确保你已经在Offer模型中定义了正确的一对多关联:

// App\Models\Offer.php
public function reports()
{
    return $this->hasMany(Report::class, 'offer_id');
}

方案1:withCount关联统计(推荐,可同时获取Offer完整信息)

适合需要同时返回Offer基础信息+对应report统计数的场景,直接在关联统计中加入日期过滤条件即可:

// 替换为你实际的日期过滤范围
$startDate = '2024-01-01';
$endDate = '2024-01-31';

$offerStats = Offer::withCount(['reports' => function ($query) use ($startDate, $endDate) {
    // 此处created_at可替换为你report表中实际的日期字段
    $query->whereBetween('created_at', [$startDate, $endDate]);
}])
->orderBy('reports_count', 'desc')
->get();

返回结果中每个Offer实例会自动携带reports_count属性,即为指定日期范围内的关联report行数。

方案2:直接查询Report表分组统计

适合只需要统计结果、不需要返回Offer其他字段的场景,性能更高:

$startDate = '2024-01-01';
$endDate = '2024-01-31';

$reportStats = Report::selectRaw('offer_id, count(*) as reports_count')
    ->whereBetween('created_at', [$startDate, $endDate])
    ->groupBy('offer_id')
    ->orderBy('reports_count', 'desc')
    ->get();

如果需要关联查询Offer的其他字段,可以加入leftJoin:

$reportStats = Report::selectRaw('reports.offer_id, count(*) as reports_count, offers.name, offers.id')
    ->leftJoin('offers', 'reports.offer_id', '=', 'offers.id')
    ->whereBetween('reports.created_at', [$startDate, $endDate])
    // MySQL5.7+需要把select的非聚合字段全部加入groupBy,避免only_full_group_by报错
    ->groupBy('reports.offer_id', 'offers.name', 'offers.id')
    ->orderBy('reports_count', 'desc')
    ->get();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 13:06:05