亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Postgres 和 Laravel 如何將列從字符串類型更改為整數?

Postgres 和 Laravel 如何將列從字符串類型更改為整數?

PHP
茅侃侃 2023-08-11 17:55:05
我正在嘗試將 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 將此列從字符串類型更改為整數類型?
查看完整描述

2 回答

?
千萬里不及你

TA貢獻1784條經驗 獲得超9個贊

您必須指定顯式轉換,因為沒有從文本或 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');

}


查看完整回答
反對 回復 2023-08-11
?
Helenr

TA貢獻1780條經驗 獲得超4個贊

即使表有行或沒有行,它仍然返回該錯誤。因此,如果您不想要原始查詢并且您的列沒有值或有但不重要,只需刪除列并創建新的列:


public function up()

{

    Schema::table('job_listings', function (Blueprint $table) {

        $table->dropColumn('company_id');

        $table->integer('company_id');

    });

}


查看完整回答
反對 回復 2023-08-11
  • 2 回答
  • 0 關注
  • 203 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號