【问题标题】:How proper change the format of date on Eloquent Model?如何正确更改 Eloquent 模型上的日期格式?
【发布时间】:2020-05-27 21:46:05
【问题描述】:

我们有一个雄辩的模型,但我们希望所有日期都采用'Y-m-d' 格式而不是'U',类似于:

/**
 * The attributes that should be mutated to dates.
 *
 * @var array
 */
protected $dates = [
    'contract_date',
    'contract_end'
];

/**
 * The storage format of the model's date columns.
 *
 * @var string
 */
protected $dateFormat = 'Y-m-d';

除了 Eloquent 模型更新功能外,它工作正常:

$contract->update($attributes);

使用 Carbon 引发异常:

  +"message": "Trailing data"
  +"exception": "InvalidArgumentException"
  +"file": "/home/vagrant/Code/vendor/nesbot/carbon/src/Carbon/Carbon.php"
  +"line": 917

使用 Eloquent 获取自定义日期格式的最佳方法是什么?

【问题讨论】:

  • $attributes 变量中有什么?
  • 一个数组,例如:[ 'contract_date' => '2020-05-01', 'contract_end' => '2020-05-31', ];
  • 你确定吗?你调用它时有 dd($attributes) 吗?
  • 是的,我正在使用测试用例和调试。另外,我确认它们存储在数据库中。我的印象是方法更新使用默认格式“U”而不是 dateFormat 上定义的格式。

标签: php laravel eloquent


【解决方案1】:

使用 Eloquent 获取自定义日期格式的最佳方法是什么?
Laravel $dateFormat 对我来说也很受欢迎。我最终改用Accessors & Mutators。

在模型::类中

use Carbon\Carbon;

// contract_date -- Accessor
public function getContractDateAttribute($value)
{
   return Carbon::parse($value)->format('Y-m-d');
}

// contract_date -- Mutator
public function setContractDateAttribute($value)
{
   $this->attributes['contract_date'] = Carbon::parse($value)->format('Y-m-d');
}

【讨论】:

    猜你喜欢
    • 2016-04-14
    • 2019-07-10
    • 1970-01-01
    • 2017-10-04
    • 2020-01-07
    • 1970-01-01
    • 2012-06-03
    • 2013-12-12
    • 1970-01-01
    相关资源
    最近更新 更多