简体   繁体   中英

Laravel : Order by string date using query builder with MySql

The table have a startDate column which is VARCHAR type, so need to get rows by ascending order using this column.

Tried this :

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

the above does not return correct order, how to pass string date in order by clouse?

Example:

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

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

You need to convert the date to MySQL format. Try to use DATE_FORMAT :

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

Gunaseelan是正确的,但是有synthax错误,请尝试以下操作:

$items = DB::table("mytable")->where('userId','=',$userId)->orderByRaw("DATE_FORMAT('d-m-Y',startDate), ASC")->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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