首页 文章

在Laravel迁移中使用新创建的列

提问于
浏览
-1

我有一个名为 listings 的表,它当前包含一个名为 closed 的列,其数据类型为 integer . 该列仅包含两个值, 1NULL .

现在,我需要将此列的数据类型修改为 timestamp ,但根据documentation,这对于 timestamp 数据类型是不可能的 . 我还想将此列的值设置为当前日期,其中前一个值为 1 ,如果前一个值包含 NULL ,则为 NULL .

这是我的策略:

  • 创建名为 closed_temp 的新列,使其默认值为当前日期

  • closed_temp 设置为 NULL closedNULL

  • 删除 closed

  • closed_temp 列重命名为 closed

这是我的代码:

public function up()
{
    Schema::table('listings', function (Blueprint $table) {
        $table->timestamp('closed_temp')->default(\Carbon\Carbon::now())->nullable();
        $listings = Listing::all();
        foreach ($listings as $listing) {
            if(!isset($listing->closed)) {
                $listing->closed_temp = NULL;
                $listing->save();
            }
        }
    });
}

但是,这给了我一些错误:

[Illuminate \ Database \ QueryException] SQLSTATE [42S22]:找不到列:1054'字段列表'中的未知列'closed_temp'(SQL:更新列表设置updated_at = 2017-06-21 04:50:5 8,closed_temp =其中listing_id = 3)[Doctrine \ DBAL \ Driver \ PDOException] SQLSTATE [42S22]:找不到列:1054'字段列表'中的未知列'closed_temp'[PDOException] SQLSTATE [42S22]:找不到列:1054未知列' closed_temp'in'字段列表'

有没有办法在迁移中使用新创建的列?如果没有,那还有什么其他选择?我也试过运行 raw_sql 查询,但得到了同样的错误 .

1 回答

  • -1

    我通过创建两个单独的迁移文件来修复此问题,为此migration order非常重要,因为创建新列 closed_temp 的迁移文件必须在包含用于更新 closed_temp 列的逻辑然后将其重命名为 closed 的迁移文件之前运行 .

    下面复制了两个迁移文件:

    class AlterListingsTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::table('listings', function (Blueprint $table) {
                $table->timestamp('closed_temp')->default(\Carbon\Carbon::now())->nullable();
            });        
    
        }
    }
    
    class AlterListingsClosedFieldTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::table('listings', function (Blueprint $table) {
                $listings = Listing::all();
                foreach ($listings as $key => $listing) {
                    if(!isset($listing->closed)) {
                        $listing->closed_temp = NULL;
                        $listing->save();
                    }
                }
                $table->dropColumn('closed');
                $table->renameColumn('closed_temp', 'closed');
            });
        }
    }
    

相关问题