2016-05-14 97 views
0

對於我的包,我試圖在我的users數據庫表中創建多個列。Array to string conversion:用戶遷移文件

我的表名變量定義是這樣的:

private function fields() 
{ 
    return $this->fields = [ 
     'id' => [ 
      'type' => 'increments', 
     ], 
     'name' => [ 
      'type' => 'string', 
      'length' => 250, 
     ], 
     'email' => [ 
      'type' => 'string', 
      'length' => 250, 
      'extra' => 'unique' 
     ], 
     'password' => [ 
      'type' => 'string', 
      'length' => 100, 
     ], 
     'access_token' => [ 
      'type' => 'string', 
      'length' => 255, 
     ], 
     'remember_token' => [ 
      'type' => 'string', 
      'length' => 100, 
     ], 
    ]; 
} 

我通過這次通過foreach循環這樣的嘗試循環:

Schema::create('users', function($table) { 
    foreach ($this->fields as $field => $value) { 
     if(!Schema::hasColumn('users', $field)) { 
      var_dump(gettype($value['type'])); 
      $table->$value['type']($field); 
     } 
    } 
}); 

當我運行php artisan migrate,我收到錯誤:Array to string conversion

$value['type']部分是問題。所以我知道這個問題,但無法弄清楚如何解決這個問題。

回答

0

首先,您需要將其保存到這樣一個變量:

Schema::create('users', function($table) { 
    foreach ($this->fields as $field => $value) { 
     if(!Schema::hasColumn('users', $field)) { 
      $type = $value['type']; 
      $table->$type($field); 
     } 
    } 
}); 
+0

哦!我試過把它放在像'$ type = $ value'這樣的變量中,我忘記了'['type']'。謝謝你的幫助! – RW24