あじちゃんの備忘録。

〜ここはメモ帳です

マイグレーションファイルの作成でエラー

  • 以下のファイルを実行
//@migrationファイル
public function up()
{
    if (!Schema::hasTable('Test')) {
        Schema::create('Test', function(Blueprint $table)
        {
            $table->engine = "InnoDB";
            $table->bigInteger('empId', 20)->unsigned()->comment('従業員ID');   //BIGINT(20) UNSIGNED PRIMARY KEY NOT NULL
            $table->bigInteger('compId', 20)->unsigned()->comment('会社ID');    //BIGINT(20) UNSIGNED
        });
    }
}
  • auto columnは設定していないのに以下のエラーが発生する.
SQLSTATE[42000]: Syntax error or access violation: 1075 Incorrect table definition; there can be only one auto column and it must be defined as a key 


  • こうするとうまくいく. 😕💭カラム長の指定がまずいの???
Schema::create('Test', function(Blueprint $table)
{
    $table->engine = "InnoDB";
    $table->bigInteger('empId', 20)->unsigned()->comment('従業員ID');   //BIGINT(20) UNSIGNED PRIMARY KEY NOT NULL
    $table->bigInteger('compId')->unsigned()->comment('会社ID');        //BIGINT(20) UNSIGNED
});
mysql> show columns from Test;
+-----------------------------+---------------------+------+-----+---------+----------------+
| Field                       | Type                | Null | Key | Default | Extra          |
+-----------------------------+---------------------+------+-----+---------+----------------+
| empId                       | bigint(20) unsigned | NO   | PRI | NULL    | auto_increment |
| compId                      | bigint(20) unsigned | NO   |     | NULL    |                |
+-----------------------------+---------------------+------+-----+---------+----------------+

🙁💭 目的は達成できたけど原因がわからずもにょる.

BIGINTは8バイト整数なので、必要記憶容量は8バイト.
桁数はマイナスを含め20桁なので、上記では自動で最大が振られたということ...?
他のファイル見ててもそんな感じだった. 目的のサイズが最大より小さくなるなら指定する感じかな?

⚠️ BIGINT(20)の20は表示幅のこと. 桁数ではない. TINYINT(1)で格納可能値の勘違いをしていた件


てか、指定していないのに[empId]が勝手にprimary keyになってるしauto_incrementになってる...
$table->primary('empId'); を指定していたところエラー( SQLSTATE[42000]: Syntax error or access violation: 1068 Multiple primary key defined )となったため外していた.
unsigndBigIntegerの場合だとprimaryもauto_incrementも自動付与はされず、自分で指定する必要があった.
指定の仕方で型は同じでも付属するオプションが違うようです...(難しい)

// [primary key][auto_increment] [tyep = "bigint(20) unsigned"]
$table-> unsigned bigInteger('Id');

// [tyep = "bigint(20) unsigned"]
$table->bigInteger('Id')->unsigned();

まとめ

😭 むずかしい!
(もはやまとめたくない. 今日は悪い子になる.) 後で読む→Laravel 5.3 Eloquent ORM 入門 2 (マイグレーション)