LoginSignup
41
44

More than 3 years have passed since last update.

【Laravel】既存テーブルのマイグレーションファイルを作成する

Last updated at Posted at 2019-02-11

Laravelで既存のテーブルを使用したい場合は、マイグレーションファイルを自分で用意する必要があります。

それを自動化するパッケージがあったので、ご紹介します。

使用パッケージ

migrations-generatorというパッケージを利用します。

migrations-generator

参考記事です。

Laravelで既存のDBからmigrationsファイルを作成する「migrations-generator」

開発環境

  • PHP 7.3.2
  • Laravel 5.7.25
  • Composer 1.8.3

手順

マイグレーションファイルの生成

worldデータベースにある下記テーブルのマイグレーションファイルを生成します。

  • city
  • country
  • countrylanguage

手順はREADMEに書かれています。
その通りに実行します。

$ composer require --dev "xethron/migrations-generator"

Laravel既存のテーブルusers, password_resetsを除いて、マイグレーションファイルを生成します。

$ php artisan migrate:generate --ignore="users,password_resets"

# 省略

 Do you want to log these migrations in the migrations table? [Y/n] :
 > Y

Migration table created successfully.

 Next Batch Number is: 1. We recommend using Batch Number 0 so that it becomes the "first" migration [Default: 0] :
 > 0

# 省略

これで、以下のマイグレーションファイルが生成されました。合わせて外部キーのマイグレーションファイルも生成されています。

  • 2019_02_10_224508_create_city_table.php
  • 2019_02_10_224508_create_country_table.php
  • 2019_02_10_224508_create_countrylanguage_table.php
  • 2019_02_10_224509_add_foreign_keys_to_city_table.php
  • 2019_02_10_224509_add_foreign_keys_to_countrylanguage_table.php

Modelの設定

試しにcityテーブルを扱うCityモデルを作成します。

$ php artisan make:model City

テーブル名が「city」のため、Modelにテーブル名を明示する必要があります。
以下、公式サイトからの引用です。

他の名前を明示的に指定しない限り、クラス名を複数形の「スネークケース」にしたものが、テーブル名として使用されます。

参考記事です。

Laravelで「Base table or view not found: 1146 Table」エラーが出るときの対処法

City.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class City extends Model
{
    protected $table = 'city';
}

これでテーブルが使用できるようになりました!

41
44
2

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
41
44