Laravel資料庫架構,可為空的外鍵
P粉805107717
P粉805107717 2023-10-17 14:43:49
0
2
467

我有這兩個資料庫表:

  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();
});

合作夥伴表將包含所有使用者元資訊,例如名字和姓氏等。

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();
});

當用戶註冊到網站時,我只需要幾個字段,即用戶名電子郵件地址密碼名字姓氏。這些只是必填欄位。

因此,合作夥伴表中的資訊可以在使用者完成網站註冊後填寫。

但是由於外鍵的結構,由於此錯誤,我無法繼續進行:

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, admin@example.com, 2016-06-09 19:41:18, 2016-06-09 19:41:18))

我知道這是由合作夥伴表所需的國家/地區表引起的。

我的問題是:是否有解決辦法,以便我可以在合作夥伴表中填寫國家/地區或任何其他非必需數據,但保留國家/地區、州等的外部表架構。

P粉805107717
P粉805107717

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!