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
相关产品推荐
相关产品推荐

