2016-06-09 54 views
7

我有两个数据库表:Laravel数据库模式,为空的外

  1. 用户表
  2. 合伙表

用户表将处理这种信息的

Schema::create('users', function (Blueprint $table) { 
     $table->increments('id')->unique(); 
     $table->string('email')->unique(); 
     $table->string('username')->unique(); 
     $table->string('password', 60); 
     $table->string('photo')->nullable(); 
     $table->integer('partner_id')->unsigned(); 
     $table->foreign('partner_id')->references('id')->on('partners'); 
     $table->rememberToken(); 
     $table->timestamps(); 
}); 

虽然Partner Tabl ES将包含所有用户的元信息,如姓氏和名字等

Schema::create('partners', function (Blueprint $table) { 

    /** 
    * Identity Columns 
    */ 
    $table->increments('id')->unique(); 
    $table->string('first_name'); 
    $table->string('middle_name')->nullable(); 
    $table->string('last_name')->nullable(); 
    $table->string('display_name')->nullable(); 
    $table->string('email')->unique()->nullable(); 
    $table->string('website')->nullable(); 
    $table->string('phone')->nullable(); 
    $table->string('mobile')->nullable(); 
    $table->string('fax')->nullable(); 
    $table->date('birthdate')->nullable(); 
    $table->longText('bio')->nullable(); 
    $table->string('lang')->nullable(); //Language 

    /** 
    * Address Columns 
    */ 
    $table->text('street')->nullable(); 
    $table->text('street2')->nullable(); 
    $table->integer('country_id')->unsigned(); // foreign 
    $table->foreign('country_id')->references('id')->on('countries'); 
    $table->integer('state_id')->unsigned(); // foreign 
    $table->foreign('state_id')->references('id')->on('country_states'); 
    $table->string('city')->nullable(); 
    $table->string('district')->nullable(); 
    $table->string('area')->nullable(); 
    $table->string('zip')->nullable(); 
}); 

当用户注册到网站,我只想要几个字段它们,usernameemail addresspasswordfirst namelast name。这些只是必填字段。

因此,合作伙伴表中的信息可以在用户完成注册到网站后填写。

但由于外键的结构,我无法进行任何进一步的,因为这个错误的:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`mytable`.`tbl_partners`, CONSTRAINT `partners_country_id_foreign` FOREIGN KEY (`country_id`) REFERENCES `tbl_countries` (`id`)) (SQL: insert into `tbl_partners` (`first_name`, `last_name`, `display_name`, `email`, `updated_at`, `created_at`) values (Jack, Wilson, admin, [email protected], 2016-06-09 19:41:18, 2016-06-09 19:41:18)) 

我知道这是这是由合作伙伴表所需的国家表原因。
我的问题是:是否有一个变通,所以我可以填补国家或合作伙伴的表上的所有非必需的数据,但将外国表模式的国家,州等

回答

23

设置country_idstate_id可空,像这样。

$table->integer('country_id')->nullable()->unsigned(); 

$table->integer('state_id')->nullable()->unsigned(); 
+2

如果您需要在创建模式后更改的字段为空,则该行应 $表 - >整数( 'COUNTRY_ID') - >可空() - >无符号() - >更改( ); – sh6210