我正在尝试将 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 字段中可能存在空格,因此您必须在转换之前进行修剪
public function up()
{
DB::statement('ALTER TABLE job_listings ALTER COLUMN
company_id TYPE integer USING (trim(company_id))::integer');
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)