【问题标题】:Postgres and Laravel how to change column from type string to integer?Postgres 和 Laravel 如何将列从字符串类型更改为整数?
【发布时间】:2020-11-10 07:43:37
【问题描述】:

我试图在 Postgres 和 Laravel 6.x 上将一列从字符串类型更改为整数。我试图通过这样的迁移来做到这一点:

    public function up()
    {
        Schema::table('job_listings', function (Blueprint $table) {
            $table->integer('company_id')->change();
        });
    }

当我运行此迁移时,我收到一个错误,该列无法自动转换为整数:

In Connection.php line 664:

  SQLSTATE[42804]: Datatype mismatch: 7 ERROR:  column "company_id" cannot be cast automatically to type integer
  HINT:  You might need to specify "USING company_id::integer". (SQL: ALTER TABLE job_listings ALTER company_id TYPE INT)


In PDOStatement.php line 123:

  SQLSTATE[42804]: Datatype mismatch: 7 ERROR:  column "company_id" cannot be cast automatically to type integer
  HINT:  You might need to specify "USING company_id::integer".


In PDOStatement.php line 121:

  SQLSTATE[42804]: Datatype mismatch: 7 ERROR:  column "company_id" cannot be cast automatically to type integer
  HINT:  You might need to specify "USING company_id::integer".

PostgreSQL 中如何指定 USING 将该列从字符串类型更改为整数?

【问题讨论】:

    标签: php laravel postgresql eloquent laravel-migrations


    【解决方案1】:

    您必须指定显式转换,因为没有从文本或 varchar 到整数的隐式(自动)转换。我不知道有一个 Laravel 函数来指定强制转换,所以我建议你使用原始 DB 语句来实现这一点。

    你可以这样做:

    public function up()
    {
        DB::statement('ALTER TABLE job_listings ALTER COLUMN 
                      company_id TYPE integer USING (company_id)::integer');
    }
    

    在某些情况下,您的文本或 varchar 字段中可能存在空格,因此您必须在转换之前进行修剪

    public function up()
    {
        DB::statement('ALTER TABLE job_listings ALTER COLUMN 
                      company_id TYPE integer USING (trim(company_id))::integer');
    }
    

    【讨论】:

    • 谢谢!你会为down 方法添加什么?
    • $table->string('company_id')->change(); 应该可以正常使用 Schema
    • SQL 字符串末尾都缺少右括号 - SQL 中的括号当前不匹配。
    • 修复了这个问题。谢谢@Mog0
    【解决方案2】:

    即使表格是否有行,它仍然会返回该错误。因此,如果您不想要原始查询并且您的列没有价值或有但不重要,只需删除列并创建新列:

    public function up()
    {
        Schema::table('job_listings', function (Blueprint $table) {
            $table->dropColumn('company_id');
            $table->integer('company_id');
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-20
      • 2015-08-02
      • 2018-10-18
      • 1970-01-01
      • 1970-01-01
      • 2012-05-07
      • 1970-01-01
      • 2023-03-16
      • 2015-12-28
      相关资源
      最近更新 更多