LoginSignup
0
1

More than 1 year has passed since last update.

laravelのMigrationでidを設定した時に別名を付ける方法

Posted at

環境

  • php:8.1
  • laravel:9.23.0

対象

  • laravelのMigrationでidを設定した時に別名を付けたい人
  • idに別名をつけてseeder実行してエラーになった人

方法

マイグレーションファイル

  • 他と同じように()の中にカラム名を記入してください
create_users_table.php
<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id('user_id')->comment('ユーザーID');
            $table->string('name')->comment('ユーザー名');
            $table->string('email')->unique()->comment('メールアドレス');
        });
    }

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

モデル

  • $primaryKeyで設定したいカラム名を指定してください ← これがポイントだと思います
User.php
<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use HasFactory;
    protected $primaryKey = 'user_id';
    protected $table = 'users';
}
0
1
0

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
0
1