繁体   English   中英

在 laravel 迁移中更改主 ID

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM