資料庫設計程序中發生錯誤,日期時間在單獨的欄位中處理,我想使用遷移進行合并。是否有一些簡單的方法可以將日期和時間欄位中的資料移動到 dateTime 欄位而不會丟失現有資料?
當前表:
id | publish_date | publish_time
--------------------------------
1 | 2021-01-01 | 10:25:00
這就是我希望它看起來的樣子,沒有資料丟失:
id | publish_date_time
----------------------
1 | 2021-01-01 10:25:00
uj5u.com熱心網友回復:
可以使用遷移來執行此操作:
您可以使用創建一個php artisan make:migration MergeDateColumns,然后執行以下操作:
class MergeDateColumns extends Migration {
public function up() {
Schema::table('your table name', function (Blueprint $table) {
$table->dateTime('publish_date_time');
});
DB::table('your table name')
->update([ 'publish_date_time' => DB::raw("CONCAT(publish_date,' ', publish_time)") ]);
Schema::table('your table name', function (Blueprint $table) {
$table->dropColumn('publish_date');
$table->dropColumn('publish_time');
});
}
public function down() {
Schema::table('your table name', function (Blueprint $table) {
$table->date('publish_date');
$table->time('publish_time');
});
DB::table('your table name')
->update([
'publish_date' => DB::raw("DATE(publish_date_time)"),
'publish_time' => DB::raw("TIME(publish_date_time)")
]);
Schema::table('your table name', function (Blueprint $table) {
$table->dropColumn('publish_date_time');
$table->dropColumn('publish_time');
});
}
}
這會在您遷移時合并列,并在您回滾時再次拆分它們。
為了安全起見,我會先備份資料,然后再在生產環境中運行它,但我認為這不會導致問題。
uj5u.com熱心網友回復:
使用 MySQL 內置TIMESTAMP(expr1,expr2)函式來組合日期/日期時間和時間運算式,并且仍然回傳datetime資料型別。
uj5u.com熱心網友回復:
您可以通過以下代碼(在方法中)簡單地做到這一點:
$posts = Post::query()->selectRaw("id, concat(publish_date,' ', publish_time) as publish_date_time")->get();
foreach ($posts as $post) {
Post::query()->where("id", $post->id)->update([
'publish_date_time' => $post->publish_date_time
]);
}
確保您已經使用遷移擁有“publish_date_time”列
uj5u.com熱心網友回復:
我想你在找這個?use 可以DB::raw用于連接。
$articals = Artical::select("*", DB::raw("CONCAT(publish_date,' ', publish_time) as publish_date_time"))->get();
所以,結果你會得到
2021-01-18 04:10:35
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/414194.html
標籤:
