【问题标题】:how to count posts for user add in one month laravel?如何计算用户在一个月 laravel 中添加的帖子?
【发布时间】:2020-01-11 08:54:49
【问题描述】:
我想计算用户在当月添加了多少帖子。我只是想得到号码。
这是我尝试的方法,但它不起作用:
$currentMonth = date('m');
$datas = DB::table("posts")
->whereRaw('MONTH(created_at) = ?' ,[$currentMonth])
->get();
【问题讨论】:
标签:
php
laravel
laravel-query-builder
【解决方案1】:
您应该在用户模型中创建一个 hasMany posts 关系并相应地访问它
这样的东西应该可以工作
$posts = auth()->user()->posts()->whereDate('created_at', now()->startOfMonth())->get();
【解决方案2】:
试试这个代码:
$startDate = date('Y-m-d H:i:s', strtotime("-1 months", strtotime(Carbon::now())));
$postCount=Post::where('user_id', Auth::user()->id)
->whereBetween('created_at',[$startDate,Carbon::now()])->count()