【问题标题】:How to store Carbon objects in MySQL using Laravel如何使用 Laravel 在 MySQL 中存储 Carbon 对象
【发布时间】:2013-11-30 20:20:00
【问题描述】:
所以,我知道 Laravel 将它们的“created_at”和“updated_at”存储为 Carbon 对象。至少,每次我尝试获取它们时,它们都以碳的形式返回。所以我有一个 Carbon 对象,我想将它存储在我的“premium_until”列中。现在,我应该怎么做呢?设置架构时应该使用$table->timestamp('premium_until'); 还是$table->date('premium_until');?另外,我可以只做$user->premium_until = $carbonObject; 还是必须将其转换为字符串?提前致谢!
【问题讨论】:
标签:
php
mysql
laravel
laravel-4
php-carbon
【解决方案1】:
Eloquent 提供了处理日期的便捷方式。
只需在 Eloquent 模型上定义 getDates 方法,它会返回列名数组,这些列名应该由 Eloquent 自动转换为 Carbon 实例!
public function getDates()
{
return array(static::CREATED_AT, static::UPDATED_AT, static::DELETED_AT, 'premium_until');
}
【解决方案2】:
现在可以在 Eloquent 模型上设置 $dates 属性,而不是定义 getDates 方法。与上一个答案相比的优点是您不需要显式(重新)定义 Eloquent 日期(例如,created_at):
protected $dates = ['premium_until'];