laravel migration best way to add foreign key

后端 未结 10 1092
梦毁少年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: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

提交回复
热议问题