2016-05-14 63 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