LaravelのMigrationでテーブルを作成する

LaravelMigration

LaravelではDB操作をmigrationコマンドで実行できます。
DBを直接触っても問題ありませんが、更新履歴をソースファイルに残せるというのは後々便利です。

 

こちらの記事を参照しました

まず最初に

まずは作業ディレクトリへ移動し、下記コマンドを実行。

$ php artisan make:migration create_table_example(今回マイグレーションで作成するファイル名)
Created Migration: 2018_07_08_092508_create_table_example

すると下記パスに今回のmigrationで作成されたファイルが配置されます。
作業ディレクトリ/database/migrations/2018_07_08_092508_create_table_example.php

ファイルの中身:

<?php

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

class CreateTableExample extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        //
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
}

migrationコマンドで実行しなくても/database/migrations/yyyy_mm_dd_his_*****.phpファイルを作成し、上記の内容をコピペすればmigration実行時にちゃんと動いてくれます。

下記は例です

up()はmigration実行時に処理され、down()はロールバック時に処理されます。
カラムの型は$table->textのように指定するのですが、公式ドキュメントに記載されているので参照してみましょう。

$table->timestamps()を記載すれば、自動的にcreated_atとupdated_atが自動的に挿入されるので便利です。

<?php

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

class CreateTableExample extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        if (!Schema::hasTable('t_example')) { // t_exampleテーブルがない場合の処理
            Schema::create('t_example', function (Blueprint $table) {
                $table->bigIncrements('id')->unsigned()->comment('ID');
                $table->string('name', 255)->comment('名前');
                $table->text('discription')->comment('説明');
                $table->unsignedTinyInteger('delete_flg')->default(0)->comment('削除フラグ');
                $table->timestamps();
            });
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        // t_exampleテーブルが存在すれば削除する
        Schema::dropIfExists('t_example');
    }
}

作成したmigrationファイルは下記コマンドで実行します。

$ php artisan migrate

もしエラーが出てしまう場合

もしエラーが出る場合は、DBの設定が間違えています。
Laravelはデフォルトだと.envからDB情報を取得しているので、まずはそこを確認してみてください。

Illuminate\Database\QueryException  : SQLSTATE[42000]: Syntax error or access violation: 1142 CREATE command denied to user 'example'@'example' for table 'migrations' (SQL: create table `migrations` (`id` int unsigned not null auto_increment primary key, `migration` varchar(255) not null, `batch` int not null) default character set utf8mb4 collate 'utf8mb4_unicode_ci')

  at /var/www/html/example/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
    660|         // If an exception occurs when attempting to run a query, we'll format the error
    661|         // message to include the bindings with SQL, which will make this exception a
    662|         // lot more helpful to the developer instead of just the database's errors.
    663|         catch (Exception $e) {
  > 664|             throw new QueryException(
    665|                 $query, $this->prepareBindings($bindings), $e
    666|             );
    667|         }
    668|

  Exception trace:

  1   PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1142 CREATE command denied to user 'example'@'example' for table 'migrations'")
      /var/www/html/example/vendor/laravel/framework/src/Illuminate/Database/Connection.php:452

  2   PDO::prepare("create table `migrations` (`id` int unsigned not null auto_increment primary key, `migration` varchar(255) not null, `batch` int not null) default character set utf8mb4 collate 'utf8mb4_unicode_ci'")
      /var/www/html/example/vendor/laravel/framework/src/Illuminate/Database/Connection.php:452

  Please use the argument -v to see more details.

LaravelMigration