laravel migration best way to add foreign key

后端 未结 10 1064
梦毁少年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:01
    Schema::create('roles',function(Blueprint $table){
    
        $table->bigIncrements('id');
        $table->string('name');
        $table->timestamps();
    
    });
    
    Schema::create('permissions',function(Blueprint $table){
    
        $table->unsignedBigInteger('role_id');
        $table->foreign('role_id')->references('id')->on('roles');
        $table->string('permission');
    
    });
    
    0 讨论(0)
  • 2020-12-09 10:03

    Laravel 7.x Foreign Key Constraints

    Laravel also provides support for creating foreign key constraints, which are used to force referential integrity at the database level. For example, let's define a user_id column on the posts table that references the id column on a users table:

    Schema::table('posts', function (Blueprint $table) {
        $table->unsignedBigInteger('user_id');
    
        $table->foreign('user_id')->references('id')->on('users');
    });
    

    Since this syntax is rather verbose, Laravel provides additional, terser methods that use convention to provide a better developer experience. The example above could be written like so:

    Schema::table('posts', function (Blueprint $table) {
        $table->foreignId('user_id')->constrained();
    });
    

    Source: https://laravel.com/docs/7.x/migrations

    0 讨论(0)
  • 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 .

    0 讨论(0)
  • 2020-12-09 10:10
    Schema::table('posts', function (Blueprint $table) {
        $table->unsignedInteger('user_id');
    
        $table->foreign('user_id')->references('id')->on('users');
    });
    
    0 讨论(0)
提交回复
热议问题