数组到字符串的转换:用户迁移文件


Array to string conversion: user migration file

对于我的包,我正在尝试在users数据库表中创建多个列。

我的表名变量定义如下:

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']部分就是问题所在。所以我知道这个问题,但不知道如何解决这个问题。

您首先需要将其保存到如下变量中:

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