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

Laravel Eloquent如何查询最新关联Post发布时间超过30天的用户

Laravel 实现查询最新帖子发布超过30天用户的方案

前置前提

确保你已经在User模型中正确配置了关联关系:

public function posts()
{
    return $this->hasMany(Post::class);
}

实现方法

方法1:使用whereHas聚合查询(适合中小数据量)

直接通过关联条件筛选符合要求的用户:

use Carbon\Carbon;

// 计算30天前的时间节点
$threshold = Carbon::now()->subDays(30);

$inactiveUsers = User::whereHas('posts', function ($query) use ($threshold) {
    $query->whereRaw('MAX(created_at) < ?', [$threshold]);
})
// 如果你需要将从未发布过帖子的用户也纳入通知范围,取消注释下面一行
// ->orWhereDoesntHave('posts')
->get();

方法2:使用withAggregate预查询(适合大数据量,性能更优)

Laravel 8及以上版本支持该方法,代码更简洁,查询效率更高:

use Carbon\Carbon;

$threshold = Carbon::now()->subDays(30);

$inactiveUsers = User::withAggregate('posts', 'max(created_at) as latest_post_at')
    ->where('latest_post_at', '<', $threshold)
    // 纳入从未发布过帖子的用户,取消注释下面一行
    // ->orWhereNull('latest_post_at')
    ->get();

批量发送邮件注意事项

如果查询到的用户数量较大,不要直接全量获取处理,使用chunk方法分批处理避免内存溢出:

User::withAggregate('posts', 'max(created_at) as latest_post_at')
    ->where('latest_post_at', '<', $threshold)
    ->chunk(200, function ($users) {
        foreach ($users as $user) {
            // 替换为你自己的通知类即可
            $user->notify(new \App\Notifications\InactivePostNotification());
        }
    });

额外提示:你可以将上述逻辑封装为Laravel命令行任务,配合任务调度每天自动执行,无需手动触发。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 23:06:05