LoginSignup
8
3

More than 1 year has passed since last update.

プログラミング初心者が書いたマイグレーションのやり方について

Posted at

はじめに

現在Laravelを学習しているプログラミング初心者の僕が
今回はマイグレーションのやり方について記載していきたいと思います。

マイグレーションとは?

マイグレーションとはデータベースのバージョン管理機能のことを指します。
PHPのスクリプトを使うことによりテーブルの作成処理などを用意することが出来るのです。

マイグレーションの手順としては以下のようになります。

  • マイグレーションファイルの作成
  • スクリプトの記述
  • マイグレーションの実行

マイグレーションファイルの作成~実行まで

現在作成しているプロジェクトに移動してから以下のコマンドを実行します。
(僕は今回peopleというファイルを作ります)

$ php artisan make:migration cretate_people_table

するとdatabaseフォルダのmigrationsフォルダの中に
xxxxx_create_people_table.phpというファイルが新たに作られていると思います。
(xxxxxには作成した日時が書いてある)

xxxxx_create_people_table.php
<?php

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

class CreatePeopleTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('people', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->timestamps();
        });
    }

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

続いては上記のコードにテーブル生成と削除の処理を記載していきます。

    public function up()
    {
        Schema::create('people', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name'); //追記
            $table->string('mail'); //追記
            $table->integer('age'); //追記
            $table->timestamps();
        });
    }

これでテーブルの生成は完了です。
テーブルの生成方法は下記の通りです。

    public function up()
    {
        Schema::create('テーブル名', function (Blueprint $table) {
            $table->('フィールド名');
        });
    }

続いてテーブルの削除処理となります。
削除処理のメソッドはすでにデフォルトで下記のコードが記述されています。

    public function down()
    {
        Schema::dropIfExists('people'); //テーブルがあれば削除
    }

ここは特に変更するポイントは御座いません。
そして最後にこの作成したファイルを基にマイグレーションを実行します

$ php artisan migrate

うまく成功すると画像のようになります
マイグレーション.png
個人的な感想ですが、マイグレーションがうまく決まった時の気持ち良さは結構好きです笑
ちなみにmigrateして上手くいかなかった場合はまとめて巻き戻すことも出来ます。

$ php artisan migrate:rollback

以上がマイグレーションの作成〜実行となります。
問題なく進めばあっという間に完成できるので良ければやってみてください!

参考記事
https://qiita.com/shosho/items/a5a5839735dfef9214b1
https://readouble.com/laravel/5.6/ja/migrations.html

8
3
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
8
3