如何使用Laravel在MySQL中存储Carbon对象


How to store Carbon objects in MySQL using Laravel

所以,我知道Laravel将他们的"created_at"answers"updated_at"存储为Carbon对象。至少,每次我试图得到它们时,它们都会以碳的形式返回。所以我有一个Carbon对象,我想把它存储在我的"premium_until"列中。现在,我该怎么做呢?设置架构时,我应该执行$table->timestamp('premium_until');还是$table->date('premium_until');?另外,我可以只做$user->premium_until = $carbonObject;吗?还是必须将其转换为字符串?提前感谢!

Eloquent提供了处理日期的方便方法
只需在Eloquent模型上定义getDates方法,该方法返回列名数组,该数组应由Eloquet自动转换为Carbon实例!

public function getDates()
{
    return array(static::CREATED_AT, static::UPDATED_AT, static::DELETED_AT, 'premium_until');
}

现在可以在Eloquent模型上设置$dates属性,而不是定义getDates方法。与前面的答案相比,优势在于您不需要明确(重新)定义Eloquent日期(例如created_at):

protected $dates = ['premium_until'];