流明禁用碳日期

问题描述 投票:0回答:1

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

 $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';
php lumen php-carbon
1个回答
1
投票

修复

可以直接在

SoldierData
课堂上投射。

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

原因

dates
属性不影响施法的原因如下。 Eloquent 类
HasAttribute
包含默认
dates
protected $dates = [];
。还有
getDates
方法

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

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

因此,这两个属性

created_at
updated_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
方法调用的。这就是打字的内部厨房。

© www.soinside.com 2019 - 2024. All rights reserved.