Laravel:使用带有MySql的查询构建器按字符串日期排序

问题描述 投票:0回答:2

该表有一个startDate列,它是VARCHAR类型,因此需要使用此列按升序获取行。

试过这个:

orderBy(DB::raw("DATE(startDate)"), 'ASC')

以上没有返回正确的顺序,如何通过clouse按顺序传递字符串日期?

例:

'startDate' => '07-Nov-2017'

$items = DB::table("mytable")->orderBy(DB::raw("DATE(startDate)"), 'ASC')->where('userId','=',$userId)->get();

php mysql laravel
2个回答
1
投票

您需要将日期转换为MySQL格式。尝试使用DATE_FORMAT

$items = DB::table("mytable")
           ->orderBy(DB::raw("DATE_FORMAT(startDate,'%d-%M-%Y')"), 'ASC')
           ->where('userId','=',$userId)
           ->get();

0
投票

Gunaseelan是对的,但是由于synthax错误,试试这个:

$items = DB::table("mytable")->where('userId','=',$userId)->orderByRaw("DATE_FORMAT('d-m-Y',startDate), ASC")->get();
© www.soinside.com 2019 - 2024. All rights reserved.