简体   繁体   中英

Change Primary ID in laravel Migration

I'm creating a table where I want to use the ID from this table "menu_items" to be added in another table

Table one: 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');

Table 2 products

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();
        });

My aim of doing this is that I can then create a relationship between the 2 tables as they have the same key?

Is there a different approach I can take? Should I create a unique key when creating a menu item and then add this to the second table?

Thank you.

Basically Laravel Eloquent do the key handling. When you have two tables which both has as key the name id, this is not a problem. Name the keys in the relation table just like this

table1_id
table2_id 

Laravel will handle this in Eloquent. You are also able to name the two columns in the relation table to what ever you want. You could define it for the relation in Eloquent. Eg

public function otherModel () {
    return $this->belongsToMany('App\Models\OtherModel', 'table_name', 'this_model_id', 'other_model_id');
}

Please have a look into: Laravel Relationship Documentation

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');
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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