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

Php Postgres和Laravel如何将列从字符串类型更改为整数?,php,laravel,postgresql,eloquent,laravel-migrations,Php,Laravel,Postgresql,Eloquent,Laravel Migrations,我正在尝试将Postgres和Laravel6.x上的列从string类型更改为integer类型。我尝试过这样的迁移: public function up() { Schema::table('job_listings', function (Blueprint $table) { $table->integer('company_id')->change(); }); } 运行此迁移时,出现一个错

我正在尝试将Postgres和Laravel6.x上的列从string类型更改为integer类型。我尝试过这样的迁移:

    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中,如何指定使用将此列从字符串类型更改为整数?

您必须指定显式转换,因为没有从text或varchar转换为整数的隐式(自动)转换。我不知道有哪种Laravel函数可以指定强制转换,所以我建议您使用raw 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()应该可以很好地处理模式