2016-06-24 24 views
0

我是新來php和laravel和MariaDB 10.1.xx.使用laravel 5.2。Laravel 5如何在select子句中使用Carbon轉換日期相關列?

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

請讓我有什麼想法,解決使用碳而不是原始查詢這個問題。

回答

0

在你的模型(Test)加保護的場$dates

class Test { 
    //... 
    protected $dates = ['created_at', 'updated_at', 'date']; 
    //... 
} 

這告訴口才,場date(和默認的時間戳字段)包含一個日期。 $entity->date現在將包含一個Carbon實例,用於Test類型的實體。您可以使用此格式的日期($entity->date->format('Ym');

你甚至可以寫一個Accessor爲你做到這一點:

class Test { 
    //... 
    public function getFormattedDateAttribute() { 
     return $this->attributes['date']->format('Ym'); 
    } 
    //... 
} 
echo $entity->formatted_date; 
0

另一種選擇是在你的模型像使用存取器

public function getDateAttribute($value){ 
    return Carbon::createFromFormat('Y-m-d', $value)->toDateTimeString(); 

} 

您可以更改或者根據需要

使用它
相關問題