laravel migration best way to add foreign key

后端 未结 10 1072
梦毁少年i
梦毁少年i 2020-12-09 09:19

Simple question: I\'m new to Laravel. I have this migration file:

Schema::create(\'lists\', function(Blueprint $table) {
    $table->increments(\'id\'); 
         


        
10条回答
  •  一整个雨季
    2020-12-09 10:06

    let's say you have two tables student and section , you can refer the following two table structure for adding foreign key and making onDelete('cascade') .

    Table -1 :

    public function up()
    {
        Schema::create('student', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('address');
            $table->string('phone');
            $table->string('about')->nullable();
            $table->timestamps();
        });
    }
    

    Table - 2:

    public function up()
    {
        Schema::create('section', function (Blueprint $table) {
            $table->id();
            $table->bigInteger('student_id')->unsigned()->index()->nullable();
            $table->foreign('student_id')->references('id')->on('student')->onDelete('cascade');
            $table->string('section')->nullable();
            $table->string('stream')->nulable();
            $table->timestamps();
        });
    }
    

    hope it will help you -:) you can read the full article from here .

提交回复
热议问题