laravel如何按日,月,年显示数据?

时间:2019-12-13 07:41:37

标签: laravel

我想显示我尝试过的日,月,年的数据,但根本不显示。

public function today()
{
    $videos = Video::whereBetween('created_at', [now(), now()->addDays(7)])
    ->orderBy('created_at')
    ->get()
    ->groupBy(function ($val) {
        return Carbon::parse($val->created_at)->format('d');
    });

    return view('video.today', compact('videos'));
}

可见

@foreach ($videos as $video)
{{ $video->title }}
@endforeach

Screenshot of the view

3 个答案:

答案 0 :(得分:0)

您在收集上进行->groupBy(),我建议在SQL上进行(MySQL解决方案):

public function today()
{
    $videos = Video::whereBetween('created_at', [now(), now()->addDays(7)])
    ->orderBy('created_at')
    ->groupBy(\DB::raw('DAY(created_at)')) //YEAR(created_at) //MONTH(created_at)
    ->get();

    return view('video.today', compact('videos'));
}

这将按SQL级的day对视频进行分组。

注意:正如@Jerodev在评论中所说,您要感染的未来视频会将您where更改为:

whereBetween('created_at', [now()->subDays(7), now()])

OR

whereDate('created_at', '>=', now()->subDays(7)->toDateString())
->whereDate('created_at', '<=', now()->toDateString())

这将提取最近7天的视频。

答案 1 :(得分:0)

  

尝试一下:

Carbon::parse($request->created_at)->format('d-m-Y');

答案 2 :(得分:0)

使用此DECLARE @DateSearch1 DATETIME='2017-03-13' DECLARE @DateSearch2 DATETIME='2017-09-25' SELECT *,DATEDIFF(DAY,r.dat1,r.dat2) daysOfRange FROM ( SELECT BillID , CASE WHEN FromDate<@DateSearch1 THEN @DateSearch1 ELSE FromDate END AS dat1, CASE WHEN ToDate>@DateSearch2 THEN @DateSearch2 ELSE ToDate END AS dat2 FROM Bills WHERE ( FromDate >= @DateSearch1 AND FromDate <= @DateSearch2 ) AND ( ToDate >= @DateSearch1 AND ToDate <= @DateSearch2 ))r 格式

DAY