Laravel Database Schema, Nullable Foreign

前端 未结 4 816
自闭症患者
自闭症患者 2020-12-15 16:52

I\'ve these two database tables:

  1. User Tables
  2. Partner Tables

User Tables will handle this kind of informations

相关标签:
4条回答
  • 2020-12-15 17:15

    With the latest version of Laravel, you can use the nullable method in conjunction of foreignKey:

    $table
          ->foreignId('other_table_id')
          ->nullable() // here
          ->references('id')
          ->on('other_table');
    
    0 讨论(0)
  • 2020-12-15 17:18

    For Laravel 7.x I use this way:

    $table->bigInteger('word_type_id')->nullable()->unsigned();
    $table->index('word_type_id')->nullable();
    $table->foreign('word_type_id')->nullable()->references('id')->on('word_types')->onDelete('cascade');
    
    0 讨论(0)
  • 2020-12-15 17:30

    Set the country_id and the state_id nullable, like so.

    $table->integer('country_id')->nullable()->unsigned();
    
    $table->integer('state_id')->nullable()->unsigned();
    
    0 讨论(0)
  • 2020-12-15 17:35

    For laravel 7.x to create a nullable foreign key use simply:

    $table->foreignId('country_id')->nullable()->constrained();
    
    $table->foreignId('state_id')->nullable()->constrained();
    

    REMEMBER: nullable should be before constrained otherwise the nullable will not be affected.

    0 讨论(0)
提交回复
热议问题