【问题标题】:How to convert string to boolean in laravel migration?如何在 laravel 迁移中将字符串转换为布尔值?
【发布时间】:2021-06-30 12:02:42
【问题描述】:

我想将字段从字符串转换为布尔值 试试这段代码:

 public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->boolean('email_permission')->change();
        $table->boolean('sms_permission')->change();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('users', function (Blueprint $table) {
        //
    });
}

但我得到了下面的错误

Doctrine\DBAL\Driver\PDOException::("SQLSTATE[42804]: Datatype mismatch: 7 ERROR:  column 
"email_permission" cannot be cast automatically to type boolean
HINT:  You might need to specify "USING email_permission::boolean".")

这是原始迁移:

   public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->string('email_permission')->nullable()->default('0');
        $table->string('sms_permission')->nullable()->default('0');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('users', function (Blueprint $table) {
        $table->dropColumn('email_permission');
        $table->dropColumn('sms_permission');
    });
}

如何将此字段类型从整数更改为布尔值?

【问题讨论】:

标签: php laravel postgresql laravel-migrations


【解决方案1】:

我用这种方式,效果很好

 public function up()
{
    Schema::table('users', function (Blueprint $table) {
        DB::statement("ALTER TABLE users 
          ALTER COLUMN email_permission DROP DEFAULT,
          ALTER COLUMN email_permission TYPE BOOLEAN USING email_permission::BOOLEAN,
          ALTER COLUMN email_permission SET DEFAULT FALSE;");
    });
}

【讨论】:

    猜你喜欢
    • 2011-02-17
    • 2012-04-02
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 2018-09-07
    • 1970-01-01
    • 2010-09-20
    相关资源
    最近更新 更多