2017-04-20 53 views
0

我試圖給我的MySQL數據庫添加參考數據。我有困難的特定表具有映射到同一個表來表示父/子關係,按我的遷移功能可爲空的外鍵:Laravel種子可空鍵外鍵

public function up() 
{ 
    Schema::create('groups', function (Blueprint $table) { 
     $table->engine = 'InnoDB'; 
     $table->increments('id'); 
     $table->integer('parent_group_id')->unsigned()->nullable(); 
     $table->foreign('parent_group_id')->references('id')->on('groups'); 
     $table->string('value'); 
     $table->softDeletes(); 
    }); 
} 

問題正在嘗試與外鍵爲NULL種子在頂級行上。如果我不在任何插入的行上包含該字段,則種子按預期工作。當我添加字段只子行,預計在每一行和錯誤同場算出來的:

[PDOException] 
SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column 
count doesn't match value count at row 2 

我無法找到如何播種值爲NULL任何引用。我解決的最後一次嘗試是:

<?php 

use Illuminate\Database\Seeder; 

class GroupsTableSeeder extends Seeder 
{ 
    /** 
    * Run the database seeds. 
    * 
    * @return void 
    */ 
    public function run() 
    { 
     DB::table('groups')->insert([ 
      [ 
       'parent_group_id' => [NULL], 
       'value' => 'Group1' 
      ], 
      [ 
       'parent_group_id' => 1, 
       'value' => 'Subgroup1' 
      ], 
      [ 
       'parent_group_id' => 2, 
       'value' => 'Subgroup2' 
      ] 
     ]); 
    } 
} 

哪個錯誤輸出到Array to string conversion。使用'[NULL]'錯誤General error: 1366 Incorrect integer value。我嘗試了其他的變化,但沒有運氣。什麼是在種子中插入NULL值的正確方法?任何幫助讚賞。問候,

回答

1

您可以只使用php null值,Laravel足夠聰明,可以將其轉換爲數據庫的空值。

DB::table('groups')->insert([ 
    [ 
     'parent_group_id' => null, 
     'value' => 'Group1' 
    ], 
    [ 
     'parent_group_id' => 1, 
     'value' => 'Subgroup1' 
    ], 
    [ 
     'parent_group_id' => 2, 
     'value' => 'Subgroup2' 
    ] 
]); 

當使用[]創建一個PHP數組,這就是爲什麼你得到這個錯誤。

+0

我發誓我試過這個,但我可能已經把它包裹在另一個錯誤。這解決了我的問題。謝謝 – nbayly