[英]Change Primary ID in laravel Migration
我正在創建一個表,我想使用該表“menu_items”中的 ID 添加到另一個表中
表一:menu_items
Schema::create('menu_items', function (Blueprint $table) {
$table->id('menu_level_item_id');
$table->timestamps();
$table->string('menu_item_name');
$table->string('menu_item_desc');
表2產品
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('product_name');
$table->string('product_desc');
$table->integer('price');
$table->integer('menu_level_item_id');
$table->timestamps();
});
我這樣做的目的是我可以在這兩個表之間創建關系,因為它們具有相同的鍵?
我可以采取不同的方法嗎? 創建菜單項時是否應該創建一個唯一鍵,然后將其添加到第二個表中?
謝謝你。
基本上 Laravel Eloquent 做密鑰處理。 當您有兩個表都以名稱 id 作為鍵時,這不是問題。 像這樣命名關系表中的鍵
table1_id
table2_id
Laravel 將在 Eloquent 中處理此問題。 您還可以將關系表中的兩列命名為您想要的任何名稱。 您可以為 Eloquent 中的關系定義它。 例如
public function otherModel () {
return $this->belongsToMany('App\Models\OtherModel', 'table_name', 'this_model_id', 'other_model_id');
}
請查看: Laravel 關系文檔
Schema::create('menu_items', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('menu_item_name');
$table->string('menu_item_desc');
table->timestamp();
});
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('product_name');
$table->string('product_desc');
$table->integer('price');
$table->unsignedBigInteger('menu_level_item_id');
$table->timestamps();
$table->foreign('menu_level_item_id')->references('id')->on('menu_items');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.