0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

マイグレーションで、useCurrentOnUpdate();を使う方法

Last updated at Posted at 2022-11-05

◎分かること

Laravelのマイグレーションで、
属性にON UPDATE CURRENT_TIMESTAMP()が付与された
カラムを作成する方法が分かる。

◎結論

$table->timestamp('updated_at')->useCurrent()->useCurrentOnUpdate();

これで
属性がON UPDATE CURRENT_TIMESTAMP()なカラム「updated_at」が作れる。

詳細

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('author_id');
            $table->string('title');
            $table->text('body');
            $table->string('thumbnail_path')->nullable(true);
            $table->timestamp('created_at')->useCurrent();
-           $table->timestamp('updated_at')->useCurrent();
+           $table->timestamp('updated_at')->useCurrent()->useCurrentOnUpdate();
            $table->timestamp('published_at')->nullable(true);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('articles');
    }
};

このまま
php artisan migrateを実行してOK。

↓phpMyAdminで見たらしっかり属性が付与されてるのが分かる。
7860be4ce98261439c95daa9602d4b39.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?