【问题标题】:How to implement laravel custom carbon timestamp?如何实现 laravel 自定义碳时间戳?
【发布时间】:2016-08-09 23:50:20
【问题描述】:

我想在我的表中为过期的“比赛”设置一个未来的时间戳。我可以毫无问题地输入时间,除非当我检索输入时,它似乎没有返回一个碳实例,而只是一个带时间的字符串?

public function store(ContestRequest $request)
{
    $input = Request::all();

    // Set the 'owner' attribute to the name of the currently logged in user(obviously requires login)
    $input['owner'] = Auth::user()->name;

    // Set the enddate according to the weeks that the user selected with the input select
    $weeks = Request::input('ends_at');

    // Add the weeks to the current time to set the future expiration date
    $input['ends_at'] = Carbon::now()->addWeeks($weeks);

    Contest::create($input);

    return redirect('contests');
}

这是我用来创建新比赛的,表格中的时间格式与 created_at 和 updated_at 字段完全相同。当我尝试以下操作时,它们似乎返回了一个 Carbon 实例:

$contest->created_at->diffForHumans()

为什么我没有返回碳实例?

我的迁移文件如下所示:

$table->timestamps();
$table->timestamp('ends_at');

【问题讨论】:

    标签: php laravel schema eloquent


    【解决方案1】:

    您只需将其添加到模型中的$dates 属性即可。

    class Contest extends Model {
        protected $dates = ['ends_at'];
    }
    

    这告诉 Laravel 将您的 ends_at 属性与处理 updated_atcreated_at 的属性相同


    @Jakobud 您不必担心覆盖created_atupdated_at。它们将与$dates 数组合并:

    public function getDates()
    {
        $defaults = array(static::CREATED_AT, static::UPDATED_AT);
        return array_merge($this->dates, $defaults);
    }
    

    static::CREATED_AT 解析为 'created_at'static::UPDATED_AT 解析为 'updated_at'

    【讨论】:

    • 上次我检查过,您需要确保在该数组中还包含 created_atupdated_at,否则您告诉 Eloquent 不要创建这些日期属性。
    • 谢谢,我从来不知道他们会被合并!
    • 感谢这完美的作品。有谁知道这可以在文档中找到吗?我很难回溯这个。
    • 不客气@Stephan-v。在soft delete section 中有所提及
    • @lukasgeiter 感谢您的指点。在这里期待laravel.com/docs/5.1/eloquent-mutators#date-mutators - 但谢谢!
    【解决方案2】:

    Laravel 仅将其默认时间戳转换为 Carboncreated_atmodified_at)。对于任何其他时间戳(例如您的 ends_at 列),您可以在您的 Contest 模型中定义一个属性访问器:

    public function getEndsAtAttribute($value)
    {
        return Carbon::createFromTimeStamp(strtotime($value));
    }
    

    当您调用$contest->ends_at 时,这将从数据库返回的datetime 字符串转换为Carbon 实例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-28
      • 2015-02-20
      • 1970-01-01
      • 2016-03-08
      相关资源
      最近更新 更多