Larabel: 5.6.40
PHP: 7.2.6
マイグレーションファイルの実行にてエラーが発生します。
エラー内容:
(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table m_series_m_shohin
add constraint m_series_m_shohin_m_series_hojin_cd_foreign
foreign key (m_series_hojin_cd
) references m_series
(hojin_cd
) on delete cascade)
Laravelを初めて触るので不明箇所が多く、内容としては簡単かもしれませんが、ご教示いただけますと幸いです。
質問:
そもそも、複合主キーを持つテーブル同士での中間ファイル作成ができるのでしょうか?
作成が可能でしたら、ご教示いただけないでしょうか。
下記2つのテーブルがあります。
現状は1商品に対して1つのシリーズのみが設定できます。(商品:シリーズ=N:1)
商品マスタ(M_SHOHIN) | 主キー |
---|---|
hojin_cd | PK |
shohin_cd | PK |
shohin_name | |
series_cd | |
del_flg | |
id | |
created_at | |
updated_at |
シリーズマスタ(M_SERIES) | 主キー |
---|---|
hojin_cd | PK |
series_cd | PK |
series_name | |
id | |
created_at | |
updated_at |
今回、改修より商品に対して複数のシリーズが登録可能となります。(商品:シリーズ=N:N)
これに伴い、中間テーブルの作成を試みましたがうまく作成できません。
作成したマイグレーションファイルが以下です。
最初は、各テーブルが持っているidカラムを利用したかったのですが、主キーに設定されていないため、
エラーになったので(おそらく)、主キーを用いる方法にしています。
<マイグレーションファイル> class CreateMSeriesMShohinTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('m_series_m_shohin', function (Blueprint $table) { $table->increments('id'); $table->string('m_series_hojin_cd'); $table->string('m_series_series_cd'); $table->string('m_shohin_hojin_cd'); $table->string('m_shohin_shohin_cd'); $table->foreign('m_series_hojin_cd')->references('hojin_cd')->on('m_series')->onDelete('cascade'); $table->foreign('m_series_series_cd')->references('series_cd')->on('m_series')->onDelete('cascade'); $table->foreign('m_shohin_hojin_cd')->references('hojin_cd')->on('m_shohin')->onDelete('cascade'); $table->foreign('m_shohin_shohin_cd')->references('shohin_cd')->on('m_shohin')->onDelete('cascade'); $table->timestamps(); }); /* Schema::create('m_series_m_shohin', function (Blueprint $table) { $table->increments('id'); $table->unsignedBigInteger('m_series_id'); $table->unsignedBigInteger('m_shohin_id'); $table->foreign('m_series_id')->references('id')->on('m_series')->onDelete('cascade'); $table->foreign('m_shohin_id')->references('id')->on('m_shohin')->onDelete('cascade'); $table->timestamps(); }); */ } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('m_series_m_shohin'); } } <モデルファイル:M_SERIES.php> class M_SERIES extends Model { //複合キーを使うなら必要 use CompositePrimaryKeyTrait; protected $table="M_SERIES"; protected $primaryKey=["hojin_cd","series_cd"]; protected $guarded=array('id'); public $incrementing=false; public $timestamps=true; public function m_shohin() { return $this->belongsToMany("App\M_SHOHIN"); } } <モデルファイル:M_SHOHIN.php> class M_SHOHIN extends Model { //複合キーを使うなら必要 use CompositePrimaryKeyTrait; protected $table="M_SHOHIN"; protected $primaryKey=["hojin_cd","shohin_cd"]; protected $guarded=array('id'); public $incrementing=false; public $timestamps=true; public function M_SERIES() { return $this->belongsToMany("App\M_SERIES"); } }
あなたの回答
tips
プレビュー