如何在select子句中使用Carbon转换日期相关的列


Laravel 5 How to convert date related column using Carbon in select clause?

我是php和laravel的新手,使用laravel 5.2和MariaDB 10.1.xx。

test表有索引和日期(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.

请告诉我如何使用carbon而不是raw查询来解决这个问题。

在您的模型(Test)中添加受保护字段$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;

另一个选择是在你的模型中使用像

这样的变量
public function getDateAttribute($value){
    return Carbon::createFromFormat('Y-m-d', $value)->toDateTimeString();
}

您可以根据需要更改或使用