2017-10-05 244 views
0

我從數據庫中獲取數據的查詢,日期格式查詢在Laravel

select mailboxtoolno,DATE_FORMAT(maileventdate,'%d %b %Y') as 
date,DATE_FORMAT(maileventdate,'%H:%i:%s') as time,mailtype from 
domiciliation_mailbox where reg_id =".$regid." order by id DESC 

我怎樣才能改變它laravel雄辯模型,

我一直在試圖改變它像,

$timeline= mailbox::select('mailboxtoolno','DATE_FORMAT(maileventdate,"%d %b %Y") as date','DATE_FORMAT(maileventdate,"%H:%i:%s") as time','mailtype') 
->where('reg_id', '=',$reg_id) 
->paginate(10); 

,但得到這樣的錯誤,

Unknown column 'DATE_FORMAT(maileventdate,"%d %b %Y")' in 'field list' 

如何在laravel中獲得日期格式的正確值

+0

您使用的日期格式中選擇查詢,因此錯誤 –

回答

1

使用raw語句。例如:

$user = User::select(DB::raw('count(*) as user_count, status'))->where('status', '=', 'active'); 

順便說一句,實際上,Laravel具有帶DateTime類型字段的增變器。所以你可以選擇正常的格式並稍後格式化。例;

$user = User::find(2); 
$date = $user->created_at->format('d M Y'); // you can display it with any format you want with this way. 

更多信息,請閱讀official documentationthis

1

Laravel不支持複雜的選擇表達式,因此您必須使用Raw Expressions。嘗試了這種方式:

$timeline= mailbox::select('mailboxtoolno',DB::raw('DATE_FORMAT(maileventdate,"%d %b %Y") as date'),DB::raw('DATE_FORMAT(maileventdate,"%H:%i:%s") as time'),'mailtype') 
->where('reg_id',$reg_id) 
->orderBy('id','DESC') 
->paginate(10); 

爲了使用->orderBy()在這個查詢,你將不得不手動設置嚴格的模式,通過comprobations到ommit秩序。不要在你的database.php配置數據庫連接陣列參數:

'strict' => true, 
     'modes'  => [ 
      'STRICT_TRANS_TABLES', 
      'NO_ZERO_IN_DATE', 
      'NO_ZERO_DATE', 
      'ERROR_FOR_DIVISION_BY_ZERO', 
      'NO_AUTO_CREATE_USER', 
      'NO_ENGINE_SUBSTITUTION' 
     ], 

或者設置strict => false(我不會做)