2017-08-04 86 views
0

我需要记录日期不是碳实例。流明禁用碳日期

$soldier = Soldier::find($id); 

dd($soldier->soldier_data->pluck('created_at')); 

运行此代码将输出:

object(Illuminate\Support\Collection)#71 (1) { ["items":protected]=> array(4) { [0]=> object(Carbon\Carbon)#66 (3) { ["date"]=> string(26) "2017-08-03 13:27:47.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" } [1]=> object(Carbon\Carbon)#65 (3) { ["date"]=> string(26) "2017-08-03 13:28:13.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" } [2]=> object(Carbon\Carbon)#77 (3) { ["date"]=> string(26) "2017-08-03 13:28:15.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" } [3]=> object(Carbon\Carbon)#63 (3) { ["date"]=> string(26) "2017-08-03 13:28:15.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" } } } 

这个返回created_at碳实例。我还排出dates阵列空,但没有机会。

class SoldierData extends Model { 

    protected $fillable = []; 

    protected $dates = []; 

    protected $table = 'soldier_data'; 

回答

1

修复

可以在SoldierData类直接投放。

protected $casts = [ 
    'created_at' => 'string', 
]; 

原因

dates属性影响铸件的原因是下列之一。雄辩类HasAttribute包含默认datesprotected $dates = [];。而getDates方法

public function getDates() 
{ 
    $defaults = [static::CREATED_AT, static::UPDATED_AT]; 

    return $this->usesTimestamps() ? array_merge($this->dates, $defaults) : $this->dates; 
} 

所以这两个属性created_atupdated_at默认情况下铸成日期没有任何定义。然后看看attributesToArray:前两个日期作为日期输出,然后它可以被覆盖。

public function attributesToArray() 
{ 
    // If an attribute is a date, we will cast it to a string after convert$ 
    // to a DateTime/Carbon instance. This is so we will get some consist$ 
    // formatting while accessing attributes vs. arraying/JSONing a model. 
    $attributes = $this->addDateAttributesToArray(
     $attributes = $this->getArrayableAttributes() 
    ); 

    $attributes = $this->addMutatedAttributesToArray(
     $attributes, $mutatedAttributes = $this->getMutatedAttributes() 
    ); 

    // Next we will handle any casts that have been setup for this model an$ 
    // the values to their appropriate type. If the attribute has a mutator$ 
    // will not perform the cast on those attributes to avoid any confusion. 
    $attributes = $this->addCastAttributesToArray(
     $attributes, $mutatedAttributes 
    ); 

此方法attributesToArrayEloquent\Model::toArray方法调用。这是类型转换的内部厨房。