Laravel 中的日期格式查询

Date format Query in 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 eloquent 型号,

我一直在努力改变它,

 $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

中获取日期格式的正确值

Laravel 不支持复杂的 select 表达式,所以你必须使用 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(),您必须手动设置严格模式以通过验证忽略顺序。在您的 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(我不会)

改用raw语句。例如:

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

顺便说一句,实际上,Laravel 具有 DateTime 类型字段的修改器。所以你可以像往常一样 select 它并在以后格式化它。例子;

$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 and this