概要
既に作成済みのテーブルへカラムを追加し、データまで入れる機会があったのでまとめます。
データの投入といえばシーダーが一般的かと思いますが、追加するカラムへどのようなデータが投入されるのかをマイグレーションファイルのみで確認できるため、今回はこの方法を採用しました。
想定
- リリース済みのサービスへの改修依頼
- 並び順カラム(sort_id)を追加し、1,2,3・・・とデータを挿入する
環境
- Laravel 8.24.0
マイグレーションファイル
<?php
use App\Models\Post;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class Modifyposts20211013 extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
// sort_idカラムの追加
Schema::table('posts', function (Blueprint $table) {
$table->unsignedInteger('sort_id');
});
// カテゴリなしのsort_idを指定
// Postレコードの追加
$postRecord = [
'name' => '投稿1',
'sort_id' => 0,
];
DB::table('posts')->insert($postRecord);
// 既存のカテゴリレコードを取得
$posts = Post::oldest('id')->get();
$counter = 1;
// 既存のカテゴリレコードへsort_idの追加
foreach ($posts as $post) {
if($post->name === '投稿1') {
continue;
}
$post->sort_id = $counter;
$post->save();
$counter++;
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
// Postレコードの削除
DB::table('posts')->where('name', '投稿1')->delete();
// sort_idカラムの削除
Schema::table('posts', function (Blueprint $table) {
$table->dropColumn('sort_id');
});
}
}
解説
use App\Models\Post;について
use Illuminate\Support\Facades\DB;
$users = DB::table('users')->get();
foreach ($users as $user) {
echo $user->name;
}
上記はマニュアルの日本語訳サイトにあるものです。DBファサードを使用して既存のレコードを取得することはできるのですが、$userはstdClassオブジェクトのインスタンスとなるため、saveメソッドやupdateメソッドが使用できずエラーが発生します。そのためuse App\Models\Post; を使用し既存レコードをコレクションとして取得してデータを保存しています。
投稿1の追加など、レコードを1件挿入する際はDBファサードを使用して簡単に行うことができます。
down()メソッドについて
// Postレコードの削除
DB::table('posts')->where('name', '投稿1')->delete();
downメソッドには追加したレコードの削除も書いておきます。
この記述がないとロールバックした際に追加したレコードが削除されないため注意です。