【问题标题】:Lumen disable carbon date流明禁用碳日期
【发布时间】:2017-08-09 02:20:24
【问题描述】:

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

 $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';

【问题讨论】:

    标签: lumen php-carbon


    【解决方案1】:

    修复

    您可以直接在SoldierData 类中进行投射。

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

    原因

    dates 属性不影响强制转换的原因如下。 Eloquent 类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方法调用的。这就是类型转换的内部厨房。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-15
      • 2016-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-25
      • 2018-03-16
      相关资源
      最近更新 更多