php – laravel – 將已存在的資料庫匯出 migration 與 seed
匯出 Migration
首先安裝這個套件,先匯出 DB Schema 到 migration
1 2 3 |
composer require --dev "xethron/migrations-generator" |
Laravel 5.5 以後的版本,下載好後就不需安裝任何的 Providers。使用方法如:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// 所有資料表 php artisan migrate:generate // 指定資料表 php artisan migrate:generate table1,table2,table3,table4,table5 // 所有資料表但排除某些表,可加參數 --ignore="table3,table4,table5" // 檢視所有可選用的參數 php artisan help migrate:generate |
不過資料表欄位的型態,若是 Enum 的時候,目前版本 v2.0.2 會出錯,請修改 src/Xethron/MigrationsGenerator/Generators/FieldGenerator.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
protected function setEnum(array $fields, $table) { foreach ($this->getEnum($table) as $column) { $column_name = isset($column->column_name) ? $column->column_name : $column->COLUMN_NAME; $column_type = isset($column->column_type) ? $column->column_type : $column->COLUMN_TYPE; $fields[$column_name]['type'] = 'enum'; $fields[$column_name]['args'] = str_replace('enum(', 'array(', $column_type); } return $fields; } |
主要是 MySQL 8 返回的欄位名稱是大寫, MariaDB 返回的是小寫,需要稍作修改就可以了。我提出了合併請求,不過我看目前開發者合併停滯在 2017 年,因為這個功能僅單次使用,我也就不再 fork 了,手改一下就好。
匯出 Seed
接著產出 seed,就下載這個套件
1 2 3 |
composer require orangehill/iseed |
一樣 Laravel 5.4 以後不需要做任何安裝設定。比較麻煩的是要個別指定匯出的資料表名稱,使用方法如
1 2 3 4 5 6 7 8 9 10 11 |
// 匯出所需資料 php artisan iseed my_table php artisan iseed my_table,another_table // 產出的 seeder class 名稱加入前綴 php artisan iseed my_table --classnamesuffix=Customizations // 強制覆蓋已存在的 seed php artisan iseed users --force |