简体   繁体   English

Laravel 中的日期格式查询

[英]Date format Query in Laravel

My query for fetching a data from database is,我从数据库中获取数据的查询是,

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

How can i change it to laravel eloquent model,我怎样才能把它改成 Laravel eloquent 模型,

I have been trying to change it like,我一直在尝试改变它,

 $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);

But got an error like,但得到了一个错误,如

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

How can i get the correct value in date format in laravel如何在laravel中以日期格式获取正确的值

Laravel doesn't support complex select expressions, so you have to use Raw Expressions . Laravel 不支持复杂的 select 表达式,所以你必须使用Raw Expressions Try in this way:以这种方式尝试:

    $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);

In order to use ->orderBy() in this query you would have to set strict modes manually to ommit order by validation.为了在此查询中使用->orderBy() ,您必须手动设置严格模式以通过验证忽略订单。 Do it in your database.php config database connection array parameters:在您的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'
        ],

Or set strict => false (I won't do it)或者设置strict => false (我不会这样做)

Use raw statement instead.请改用raw语句。 For example:例如:

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

By the way actually, Laravel has mutator for field with DateTime type.顺便说一句,Laravel 具有用于 DateTime 类型字段的修改器。 So you can select it as normal and format it later.因此,您可以正常选择它并稍后对其进行格式化。 Example;例子;

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

More information read the official documentation and this更多信息阅读官方文档这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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