Laravel 迁移中的时间格式?

Jon*_*nas 9 php time laravel

我想要一个输入,您可以在其中以 EU 格式输入时间,例如 12:00 或 21:34。(hh:mm) 我该怎么做?

Schema::create('posts', function (Blueprint $table) {
    $table->increments('id');
    $table->string('title');
    $table->string('arena');
    $table->date("h,i"('beginn'));
    $table->timestamps();
});
Run Code Online (Sandbox Code Playgroud)

这是我所拥有的,但显然是错误的。

AH.*_*and 10

在 laravel 5.6 中,你有这个新功能,你可以投射你的时间戳,所以你的迁移应该是这样的

Schema::create('posts', function (Blueprint $table) {
    $table->increments('id');
    $table->string('title');
    $table->string('arena');
    $table->timestamp("begin");
    $table->timestamps();
});
Run Code Online (Sandbox Code Playgroud)

在您的Post模型中,您可以简单地执行以下操作:

protected $casts = [
    'begin' => 'date:hh:mm'
];
Run Code Online (Sandbox Code Playgroud)

编辑
如果您不使用 laravel 5.6,您可以使用Accessors & Mutators轻松操作数据库上的设置数据或从数据库中获取数据,以便您可以执行以下操作

public function getBeginAttribute($date)
{
    return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('hh:mm');
}
Run Code Online (Sandbox Code Playgroud)

每次您在刀片中或任何类似的地方回显它时,{{ $post->begin }}它都会自动为您更改格式。

希望有帮助。


khe*_*gmi 10

您可以使用$table->time('field_name');

Schema::create('posts', function (Blueprint $table) {
   $table->increments('id');
   $table->string('title');
   $table->string('arena');
   $table->time("begin");
   $table->timestamps();
});
Run Code Online (Sandbox Code Playgroud)