简体   繁体   English

在whereBetween查询中将laravel中的created_at列转换为ymd格式

[英]convert created_at column in laravel to y-m-d format in whereBetween query

this is my controller 这是我的控制器

public function index(){
    $products = Order::whereHas('user', function ($query) {
    if(request()->has('d') && request()->get('d')){
        $arr = [
           'start' => Carbon::parse(substr(request()->get('d'), 4, 11))->format('Y-m-d'),
           'end' =>  Carbon::parse(substr(request()->get('d'), 64, -44))->format('Y-m-d')
                ];
            $builder = $query->whereBetween('created_at', [$arr['start'],$arr['end']]);
           }
        });
   return OrdersResource::collection($orders->latest()->paginate(5));
    }

my array $arr looks like this 我的数组$arr看起来像这样

array:2 [
  "start" => "2018-08-07"
  "end" => "2018-08-09"
]

How can i change the created_at (which is a datetime) column in laravel to only Year month day format 我如何将Laravel中的created_at (which is a datetime)列更改为仅年月日格式

I need to convert the created_at to that format in order to perform the whereBetween query of laravel because it didn't give me the exact result 我需要将created_at转换为该格式,以便执行laravel的whereBetween查询,因为它没有提供确切的结果

Instead of change the format of the created_at column, I suggest that you should update the start and end to beginning of the first date and the ending of the last date. 建议您不要将created_at列的格式更改为第一个日期的startend以及end一个日期的结束。 The Carbon objects should be passed to the whereBetween method instead of their string representation. Carbon对象应该传递给whereBetween方法,而不是它们的字符串表示形式。

$arr = [
   'start' => Carbon::parse(substr(request()->get('d'), 4, 11))->startOfDay(),
   'end' =>  Carbon::parse(substr(request()->get('d'), 64, -44))->endOfDay()
];

// Both `start` and `end` are Carbon objects
$builder = $query->whereBetween('created_at', [$arr['start'],$arr['end']]);

You can used mysql DATE() function 您可以使用mysql DATE()函数

$builder = $query->whereBetween(DB::raw('DATE(created_at)'), [$arr['start'],$arr['end']]);

if you want to change the date format, DATE_FORMAT(created_at, '%Y-%m-%d') 如果要更改日期格式DATE_FORMAT(created_at, '%Y-%m-%d')

Dont forget to import DB 不要忘记导入DB

use DB;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM