流明禁用碳日期

时间:2017-08-04 03:58:16

标签: lumen php-carbon

我需要记录日期不是碳实例。

scope="{parent_data}"

运行此代码将输出:

 $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

1 个答案:

答案 0 :(得分:1)

<强>修正

您可以直接在SoldierData课程中投射。

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

原因

dates属性不影响强制转型的原因如下。 Eloquent class 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
    );

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