我是 php 和 laravel 的新手,并且使用 laravel 5.2 和 MariaDB 10.1.xx。
测试表有索引和日期(yyyymmdd)列。
我想将日期格式从 yyyymmdd 转换为 YYYYmm,而不在 select 子句中使用原始查询。
我尝试如下:
$test = DB::table('test')
->select( 'idx',Carbon::parse('date')->format('Ym') );
并出现如下错误:
DateTime::__construct(): Failed to parse time string (date) at position 0 (n): The timezone could not be found in the database.
请告诉我使用碳而非原始查询来解决此问题的任何想法。
最佳答案
在您的模型(Test
)中添加 protected 字段$dates
:
class Test {
//...
protected $dates = ['created_at', 'updated_at', 'date'];
//...
}
这告诉 Eloquent 字段date
(和默认的时间戳字段)包含一个日期。 $entity->date
现在将包含 Test
类型实体的 Carbon
实例。您可以使用它来格式化日期 ($entity->date->format('Ym');
)
你甚至可以写一个 Accessor为您执行此操作:
class Test {
//...
public function getFormattedDateAttribute() {
return $this->attributes['date']->format('Ym');
}
//...
}
echo $entity->formatted_date;
关于php - Laravel 5 如何在 select 子句中使用 Carbon 转换日期相关列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38020411/