Home > Mobile >  how to set foreign key in migration laravel7 [closed]
how to set foreign key in migration laravel7 [closed]

Time:09-24

how to set foreign key in migration laravel 7

CodePudding user response:

try this

 public function up()
        {
            Schema::create('tablename', function (Blueprint $table) {
                $table->increments('id');
                $table->string('name');
                $table->index('created_by');
                $table->index('updated_by');
                $table->timestamps();
                $table->softDeletes();
                $table->foreign('created_by')->references('id')->on('users');
                $table->foreign('updated_by')->references('id')->on('users');
            });
        }

CodePudding user response:

To set the foreign keys you have to use $table->foreignId('field') inside the migration, and then create a migration to apply them.

I'll give you a small example:

  • table_1
public function up()
    {
        Schema::create('table_1', function (Blueprint $table) {
            $table->bigIncrements('id');  // bigIncrements indicate a Primary Key
            $table->string('field1', 5);
            $table->string('filed2', 5);
            $table->foreignId('id_table2'); // foreign key, references on table 2
            $table->timestamps();
        });
    }

well you need create a migration called foreign_table, and now:

public function up(){

   Schema::table('table_1', function(Blueprint $table){
      $table->foreign('id_table2')->references('id')->on('table_2')->onUpdate('restrict')->onDelete('restrict');
     });
}

In this migration you can set all the foreign keys in the same way.

  • Related