【问题标题】:Array to string conversion: user migration file数组到字符串的转换:用户迁移文件
【发布时间】:2016-05-14 15:39:35
【问题描述】:

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

【问题讨论】:

    标签: php arrays laravel laravel-5


    【解决方案1】:

    您首先需要将它保存到这样的变量中:

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

    【讨论】:

    • 哦!我试过把它放在像$type = $value 这样的变量中,我忘记了['type']。感谢您的帮助!
    猜你喜欢
    • 2015-10-06
    • 2019-11-05
    • 1970-01-01
    • 2015-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2017-10-27
    相关资源
    最近更新 更多