Postgres 和 Laravel 如何将列从字符串类型更改为整数?

Postgres and Laravel how to change column from type string to integer?

我正在尝试在 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 将此列从字符串类型更改为整数?

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

你可以这样做:

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

在某些情况下,您的文本或 varchar 字段中可能会有空格,因此您必须 trim 在转换前

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

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

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