首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >碳排放若干个月

碳排放若干个月
EN

Stack Overflow用户
提问于 2021-11-24 10:52:21
回答 2查看 113关注 0票数 0

有办法跳过某个月吗?我只需要展示一月,二月,九月,十月,十一月和十二月。

这是我的密码:

代码语言:javascript
运行
复制
$emptyMonth = ['count' => 0, 'month' => 0];

for ($i = 1; $i <= 12; $i++) {
    $emptyMonth['month'] = $i;
    $monthlyArray[$i - 1] = $emptyMonth;
}

$data = DB::table('doc')
    ->select(DB::raw('count(*) as count,MONTH(created_at) as month'))
    ->where('status', 'done')
    ->where('created_at', '>=', Carbon::parse('first day of january'))
    ->where('created_at', '<=', Carbon::parse('last day of december'))
    ->whereyear('created_at', Carbon::now())
    ->groupBy('month')
    ->orderBy('month')
    ->get()
    ->toarray();

foreach ($data as $key => $array) {
    $monthlyArray[$array->month - 1] = $array;
}

$result = collect($monthlyArray)->pluck('count');

有没有一种方法可以跳过或不显示一些具体的一个月?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-11-24 11:05:04

您可以使用whereMonth

代码语言:javascript
运行
复制
  $data = DB::table('doc')
            ->select(DB::raw('count(*) as count,MONTH(created_at) as month'))
            ->where('status', 'done')
            ->where('created_at', '>=', Carbon::parse('first day of january'))
            ->where('created_at', '<=', Carbon::parse('last day of december'))
            ->whereyear('created_at', Carbon::now())
            ->where(function($query){
                $query->whereMonth('created_at',1)
                    ->orWhereMonth('created_at',2)
                    ->orWhereMonth('created_at',9); // extra
            })
            ->groupBy('month')
            ->orderBy('month')
            ->get()
            ->toarray();

或者简单地使用raw和月份 mysql函数进行操作:

代码语言:javascript
运行
复制
  $query->whereIn(DB::raw('MONTH(created_at)'),[1,2,3,9]);
票数 1
EN

Stack Overflow用户

发布于 2021-11-24 11:04:43

你可以在前排做这个过滤器。假设您将月份作为数据库中的一个数字:

代码语言:javascript
运行
复制
foreach ($data as $key => $array) {
   if(in_array($array->month, [1,2,9,10,11,12]))
   {
       $monthlyArray[$array->month - 1] = $array;
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70094766

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档