Skip to content
Advertisement

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.

Advertisement

Answer

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. E.g.

public function otherModel () {
    return $this->belongsToMany('AppModelsOtherModel', 'table_name', 'this_model_id', 'other_model_id');
}

Please have a look into: Laravel Relationship Documentation

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement