3
2

More than 3 years have passed since last update.

【Laravel7.x】Migrationを用いてテーブルを作成。Seederを用いてデータを投入する

Last updated at Posted at 2020-03-22

前提環境

Laravel7.x環境を構築。Welcomeページが表示された状態から開始。
その他、DBの設定等も済み。詳細は以下参照。

【準備編】https://qiita.com/katsuhito_01/items/db5b9581a2b6af6dc803
【導入編】https://qiita.com/katsuhito_01/items/439e3af4cea8ff00832c

Migrationを用いてテーブルを作成

まずはMigrationを用いて参照するテーブルを作成する。今回は都道府県マスタを作成。

Migration作成

Laravelプロジェクトのディレクトリ内にて、以下コマンドを実行

# php artisan make:migration create_mst_prefectures_table
Created Migration: 2020_03_22_163920_create_mst_prefectures_table

すると、database\migrations\日付_create_mst_prefectures_table.phpというファイルが作成される。
作成されたファイルをいじり、作成するテーブルの構造を記述する。
今回は以下のように記述。

【参考】:https://readouble.com/laravel/7.x/ja/migrations.html

database\migrations\日付_create_mst_prefectures_table.php
<?php

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

class CreateMstPrefecturesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('mst_prefectures', function (Blueprint $table) {
            $table->integer('id')->primary();
            $table->string('name', 10);
            $table->string('name_kana', 10);
            $table->timestamps();
        });
    }

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

Migration実行

構造を記述したら、Migrationを実行。

# php artisan migrate
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table (0.02 seconds)
Migrating: 2019_08_19_000000_create_failed_jobs_table
Migrated:  2019_08_19_000000_create_failed_jobs_table (0.01 seconds)
Migrating: 2020_03_22_163920_create_mst_prefectures_table
Migrated:  2020_03_22_163920_create_mst_prefectures_table (0.01 seconds)

MySQLに入り、テーブルを確認。

mysql> show tables;
+-----------------------+
| Tables_in_mypage01_db |
+-----------------------+
| failed_jobs           |
| migrations            |
| mst_prefectures       |
| users                 |
+-----------------------+
4 rows in set (0.00 sec)

mysql> desc mst_prefectures;
+------------+-------------+------+-----+---------+-------+
| Field      | Type        | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| id         | int(11)     | NO   | PRI | NULL    |       |
| name       | varchar(10) | NO   |     | NULL    |       |
| name_kana  | varchar(10) | NO   |     | NULL    |       |
| created_at | timestamp   | YES  |     | NULL    |       |
| updated_at | timestamp   | YES  |     | NULL    |       |
+------------+-------------+------+-----+---------+-------+
5 rows in set (0.00 sec)

出来てますね!

Seederを用いてテーブルにデータを投入

市区町村マスタができたので、Seederを用いてデータを投入する。

Modelを作成する

まずはModelを作成。
以下実行で、app直下にModelが作成される。
とりあえず今は何も書かない。

php artisan make:model MstPrefecture

ちなみに作成されたModelの中身を見てみると、空のクラスがあるだけ。
テーブルとの紐づけを明示する記述がどこにもない。

app\MstPrefecture.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class MstPrefecture extends Model
{
    //
}

以下、公式ドキュメントの記述。

他の名前を明示的に指定しない限り、クラス名を複数形の「スネークケース」にしたものが、テーブル名として使用されます。今回の例で、EloquentはFlightモデルをflightsテーブルに保存します。モデルのtableプロパティを定義し、カスタムテーブル名を指定することもできます。

【引用元】https://readouble.com/laravel/5.7/ja/eloquent.html

今回でいうと、「MstPrefectur」を「mst_prefectures」と自動的に結び付けてつけてくれる。
「おせっかいだ」と思った方は、Modelのクラス内に以下記述を追加することで、Modelとテーブルを明示的に紐づけることができる。

app\MstPrefecture.php
protected $table = 'テーブル名';

Seeder作成

続いてSeederを作成。

# php artisan make:seeder MstPrefecturesSeeder
Seeder created successfully.

以下のファイルが作成される。
database\seeds\MstPrefecturesSeeder.php

早速中身をいじり、投入するデータを記述する。

database\seeds\MstPrefecturesSeeder.php
<?php

use Illuminate\Database\Seeder;
use App\MstPrefecture;

class MstPrefecturesSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        MstPrefecture::insert([
            ['id' =>  1, 'name' => '北海道', 'name_kana' => 'ホッカイドウ', 'created_at' => now(), 'updated_at' => now()],
            ['id' =>  2, 'name' => '青森県', 'name_kana' => 'アオモリケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' =>  3, 'name' => '岩手県', 'name_kana' => 'イワテケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' =>  4, 'name' => '宮城県', 'name_kana' => 'ミヤギケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' =>  5, 'name' => '秋田県', 'name_kana' => 'アキタケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' =>  6, 'name' => '山形県', 'name_kana' => 'ヤマガタケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' =>  7, 'name' => '福島県', 'name_kana' => 'フクシマケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' =>  8, 'name' => '茨城県', 'name_kana' => 'イバラキケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' =>  9, 'name' => '栃木県', 'name_kana' => 'トチギケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 10, 'name' => '群馬県', 'name_kana' => 'グンマケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 11, 'name' => '埼玉県', 'name_kana' => 'サイタマケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 12, 'name' => '千葉県', 'name_kana' => 'チバケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 13, 'name' => '東京都', 'name_kana' => 'トウキョウト', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 14, 'name' => '神奈川県', 'name_kana' => 'カナガワケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 15, 'name' => '新潟県', 'name_kana' => 'ニイガタケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 16, 'name' => '富山県', 'name_kana' => 'トヤマケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 17, 'name' => '石川県', 'name_kana' => 'イシカワケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 18, 'name' => '福井県', 'name_kana' => 'フクイケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 19, 'name' => '山梨県', 'name_kana' => 'ヤマナシケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 20, 'name' => '長野県', 'name_kana' => 'ナガノケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 21, 'name' => '岐阜県', 'name_kana' => 'ギフケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 22, 'name' => '静岡県', 'name_kana' => 'シズオカケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 23, 'name' => '愛知県', 'name_kana' => 'アイチケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 24, 'name' => '三重県', 'name_kana' => 'ミエケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 25, 'name' => '滋賀県', 'name_kana' => 'シガケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 26, 'name' => '京都府', 'name_kana' => 'キョウトフ', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 27, 'name' => '大阪府', 'name_kana' => 'オオサカフ', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 28, 'name' => '兵庫県', 'name_kana' => 'ヒョウゴケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 29, 'name' => '奈良県', 'name_kana' => 'ナラケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 30, 'name' => '和歌山県', 'name_kana' => 'ワカヤマケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 31, 'name' => '鳥取県', 'name_kana' => 'トットリケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 32, 'name' => '島根県', 'name_kana' => 'シマネケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 33, 'name' => '岡山県', 'name_kana' => 'オカヤマケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 34, 'name' => '広島県', 'name_kana' => 'ヒロシマケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 35, 'name' => '山口県', 'name_kana' => 'ヤマグチケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 36, 'name' => '徳島県', 'name_kana' => 'トクシマケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 37, 'name' => '香川県', 'name_kana' => 'カガワケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 38, 'name' => '愛媛県', 'name_kana' => 'エヒメケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 39, 'name' => '高知県', 'name_kana' => 'コウチケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 40, 'name' => '福岡県', 'name_kana' => 'フクオカケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 41, 'name' => '佐賀県', 'name_kana' => 'サガケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 42, 'name' => '長崎県', 'name_kana' => 'ナガサキケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 43, 'name' => '熊本県', 'name_kana' => 'クマモトケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 44, 'name' => '大分県', 'name_kana' => 'オオイタケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 45, 'name' => '宮崎県', 'name_kana' => 'ミヤザキケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 46, 'name' => '鹿児島県', 'name_kana' => 'カゴシマケン', 'created_at' => now(), 'updated_at' => now()],
            ['id' => 47, 'name' => '沖縄県', 'name_kana' => 'オキナワケン', 'created_at' => now(), 'updated_at' => now()]
        ]);
    }
}

実行するSeederに追加

投入するデータの記述ができたら、以下を編集。
実行するSeederとして追加しておく。
database\seeds\DatabaseSeeder.php

database\seeds\DatabaseSeeder.php
<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $this->call(MstPrefecturesSeeder::class);
    }
}

Seederを実行

まずはComposerオートローダを再作成。
基本的に新しいクラスを追加したときは、このコマンドを実行しておく

# composer dump-autoload
Package manifest generated successfully.
Generated optimized autoload files containing 4098 classes

そしてSeederを実行。

# php artisan db:seed
Seeding: MstPrefecturesSeeder
Seeded:  MstPrefecturesSeeder (0.06 seconds)
Database seeding completed successfully.

MySQLよりテーブルを見てみると…

mysql> select * from mst_prefectures order by id;
+----+--------------+--------------------+---------------------+---------------------+
| id | name         | name_kana          | created_at          | updated_at          |
+----+--------------+--------------------+---------------------+---------------------+
|  1 | 北海道       | ホッカイドウ       | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
|  2 | 青森県       | アオモリケン       | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
|  3 | 岩手県       | イワテケン         | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
|  4 | 宮城県       | ミヤギケン         | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
|  5 | 秋田県       | アキタケン         | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
|  6 | 山形県       | ヤマガタケン       | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
|  7 | 福島県       | フクシマケン       | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
|  8 | 茨城県       | イバラキケン       | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
|  9 | 栃木県       | トチギケン         | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 10 | 群馬県       | グンマケン         | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 11 | 埼玉県       | サイタマケン       | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 12 | 千葉県       | チバケン           | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 13 | 東京都       | トウキョウト       | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 14 | 神奈川県     | カナガワケン       | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 15 | 新潟県       | ニイガタケン       | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 16 | 富山県       | トヤマケン         | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 17 | 石川県       | イシカワケン       | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 18 | 福井県       | フクイケン         | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 19 | 山梨県       | ヤマナシケン       | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 20 | 長野県       | ナガノケン         | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 21 | 岐阜県       | ギフケン           | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 22 | 静岡県       | シズオカケン       | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 23 | 愛知県       | アイチケン         | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 24 | 三重県       | ミエケン           | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 25 | 滋賀県       | シガケン           | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 26 | 京都府       | キョウトフ         | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 27 | 大阪府       | オオサカフ         | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 28 | 兵庫県       | ヒョウゴケン       | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 29 | 奈良県       | ナラケン           | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 30 | 和歌山県     | ワカヤマケン       | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 31 | 鳥取県       | トットリケン       | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 32 | 島根県       | シマネケン         | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 33 | 岡山県       | オカヤマケン       | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 34 | 広島県       | ヒロシマケン       | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 35 | 山口県       | ヤマグチケン       | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 36 | 徳島県       | トクシマケン       | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 37 | 香川県       | カガワケン         | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 38 | 愛媛県       | エヒメケン         | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 39 | 高知県       | コウチケン         | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 40 | 福岡県       | フクオカケン       | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 41 | 佐賀県       | サガケン           | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 42 | 長崎県       | ナガサキケン       | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 43 | 熊本県       | クマモトケン       | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 44 | 大分県       | オオイタケン       | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 45 | 宮崎県       | ミヤザキケン       | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 46 | 鹿児島県     | カゴシマケン       | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
| 47 | 沖縄県       | オキナワケン       | 2020-03-23 03:17:52 | 2020-03-23 03:17:52 |
+----+--------------+--------------------+---------------------+---------------------+
47 rows in set (0.00 sec)

入ってますね!
今回はDatabaseSeeder記述のSeederをすべて実行する形でしたが、以下のように個別に実行することも可能。

php artisan db:seed --class=MstPrefecturesSeeder

次回から、CRUDを作っていきましょうか。

3
2
1

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