【问题标题】:laravel date and time column concat to datetime columnlaravel 日期和时间列连接到日期时间列
【发布时间】:2022-01-18 10:38:56
【问题描述】:

数据库设计期间发生错误,日期时间在单独的字段中处理,我想使用迁移进行合并。 是否有一些简单的方法可以将日期和时间字段中的数据移动到 dateTime 字段而不丢失现有数据?

当前表:

id | publish_date | publish_time
--------------------------------
1  | 2021-01-01   | 10:25:00

这就是我想要的样子,不会丢失数据

id | publish_date_time
----------------------
1  | 2021-01-01 10:25:00

【问题讨论】:

  • 您期待的是 laravel 还是 SQL 的答案?
  • 首先是laravel,但我也喜欢听sql
  • 哪个 dbms?在日期/时间方面,许多产品远不符合 ANSI SQL。
  • 5.7.36 - MySQL 社区服务器 (GPL)

标签: php mysql sql laravel migration


【解决方案1】:

可以使用迁移来执行此操作:

您可以使用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');
       });
    } 

}

这会在您迁移时合并列,并在您回滚时再次拆分它们。

为了安全起见,我会先备份数据,然后再将其用于生产环境,但我认为这不会导致问题。

【讨论】:

    【解决方案2】:

    您可以通过以下代码(在方法中)简单地做到这一点:

    $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”列

    【讨论】:

      【解决方案3】:

      我想你正在寻找这个? use 可以使用DB::raw 进行拼接。

      $articals = Artical::select("*", DB::raw("CONCAT(publish_date,' ', publish_time) as publish_date_time"))->get();
      

      所以,结果你会得到

      2021-01-18 04:10:35
      

      【讨论】: