我从数据库中获取数据的查询是,
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 eloquent model
我一直试图改变它,
$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)
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忽略顺序。在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
(我不会这样做)
答案 1 :(得分:1)
请改用raw
语句。例如:
$user = User::select(DB::raw('count(*) as user_count, status'))->where('status', '=', 'active');
实际上,Laravel在DateTime类型的字段中有mutator。因此,您可以正常选择它并在以后格式化。实施例;
$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 documentation和this