【问题标题】:What is the best way to change a column type in Laravel migration?在 Laravel 迁移中更改列类型的最佳方法是什么?
【发布时间】:2016-11-12 10:46:04
【问题描述】:

我的数据库中有一个用户表:

        $table->increments('id');
        $table->string('fullName');
        $table->string('email')->unique();
        $table->string('password', 50);
        $table->enum('role',['boss','employee','customer'])->default('customer');
        $table->rememberToken();
        $table->timestamps();

我需要将“角色”列类型更改为“文本”,然后在 Laravel 中运行新的迁移。如果我不想对以前的数据产生影响,那么最好的方法是什么。

【问题讨论】:

    标签: php laravel laravel-5 laravel-migrations


    【解决方案1】:

    你可以尝试:

    1. 创建一个名为“roleTemp”的新文本列
    2. 运行查询为每条记录设置此列 - 基于“角色”列
    3. 删除“角色”列
    4. 将“roleTemp”重命名为“role”

    现在只需按原样更改您的数据库架构:

    $table->increments('id');
    $table->string('fullName');
    $table->string('email')->unique();
    $table->string('password', 50);
    $table->string('role');
    $table->rememberToken();
    $table->timestamps();
    

    基本上,您将角色值复制到(临时)列并重命名。至少它是安全的,不会花费很多时间。

    【讨论】:

      【解决方案2】:

      就像下面这样简单,用这一行创建一个新的迁移。请注意 ->change() 函数,它使其成为 ALTER 查询。

      Schema::table('usertable', function (Blueprint $table) {
          $table->string('role')->default('author')->change();
      });
          
      

      记住 string() 默认的大小是 255,如果你的枚举值大于这个值,它会将枚举值截断为 255 个字符。

      更新: 您需要安装 doctrine/dbal 才能使其正常工作,请参阅 Laravel Migration - Modify Columns

      要安装教义/dbal,只需执行composer require doctrine/dbal

      注意:目前不支持修改表中也具有枚举类型列的任何列。

      【讨论】:

      • 我采纳了你的建议,但遇到了这个错误:[Doctrine\DBAL\DBALException] Unknown database type enum requested, Doctrine\DBAL\Platforms\MySqlPlatform may not support it.
      • 查看我的更新,这是正确的 laravally 方式。
      • 我进行了安装,但没有成功!在您的链接([laravel.com/docs/master/migrations#modifying-columns])中,您可以阅读:Modifying any column in a table that also has a column of type enum is not currently supported.
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-15
      • 2020-05-08
      • 1970-01-01
      • 1970-01-01
      • 2019-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多