laravel 如何获取本年度的所有记录?

yhuiod9q  于 2023-05-30  发布在  其他
关注(0)|答案(5)|浏览(220)

如何获取今年的所有文章?

Articles::all()->where('created_at',$current_year);
8dtrkrch

8dtrkrch1#

你可以这样做:

Articles::whereBetween('created_at', [
    Carbon::now()->startOfYear(),
    Carbon::now()->endOfYear(),
]);

另一种方法是使用whereYear(),如@xhulio answer。但我建议你使用这段代码,因为它更易读:

Articles::whereYear('created_at', date('Y'))->get();
w8ntj3qf

w8ntj3qf2#

尝试以下查询

Articles::whereYear('created_at', '=', Carbon::parse($date)->format('Y'))->get();

Laravel有辅助函数whereDatewhereDaywhereMonthwhereYear来更好地处理日期时间查询。

ljo96ir5

ljo96ir53#

通过单线 Carbon 获得数据

Articles::whereYear('created_at', Carbon::now()->year)->get();
goqiplq2

goqiplq24#

我发现这种方法收集所有的年份只是好的

@if(isset($years) && $years != '')
                    @foreach($years as $yrs)
                        @php($year[] = $yrs->created_at)
                    @endforeach
                    @if(isset($year))
                        @php( $collection = collect($year)->unique()->values()->all())
                            @foreach($collection as $created)
                                @php($year_only[] = $created->format('Y'))
                            @endforeach
                            @php( $collections = collect($year_only)->unique()->values()->all())
                            @foreach($collections as $created_year)
                                @if($created != '')
                                    <div class="lab-item">
                                        <div class="lab-inner" style="border: #ee3725 2px solid;border-radius: 25px;background: bisque;">
                                            <div class="lab-content">
                                                <h4><a href="{{ url('years') }}/{{ $created_year }}"> {{ $created_year }} </a></h4>
                                            </div>
                                        </div>
                                    </div>
                                @endif
                            @endforeach
                    @endif
                @endif
khbbv19g

khbbv19g5#

/*In this code SurveyResult is model name and survey_results is table name and 
date('Y') mean current year. */
/* I hope its helpful for you :) */

SurveyResult::whereYear('survey_results.created_at', date('Y'))->get();

相关问题