I would like to duplicate a column on my existing seasons
table using a migration in Laravel 5.5.
I can do it using SQL running these two queries:
ALTER TABLE seasons ADD uploader_channel_partner_id BIGINT NULL
then
UPDATE seasons set seasons.uploader_channel_partner_id = seasons.channel_partner_id
I am creating a system where you can transfer the ownership of videos while keeping the original uploader stored.
The up function of my migration currently just has this inside it:
Schema::create('seasons', function (Blueprint $table) { $table->unsignedBigInteger('uploader_channel_partner_id'); $table->foreign('uploader_channel_partner_id')->references('id')->on('channel_partners'); });
EDIT:
I’ve made it work with this but it’s slow and ugly and I’m sure there is a better way:
public function up() { Schema::table('seasons', function (Blueprint $table) { $table->unsignedBigInteger('uploader_channel_partner_id')->after('channel_partner_id')->nullable(); $table->foreign('uploader_channel_partner_id')->references('id')->on('channel_partners'); }); $seasons = Season::withTrashed()->get(); foreach ($seasons as $key => $season) { $season->uploader_channel_partner_id = $season->channel_partner_id; $season->save(); } }
Answer
You can use DB::raw()
to force Sql
to use another column instead of a string value.
Season::withTrashed() ->update([ 'uploader_channel_partner_id' => DB::raw('`channel_partner_id`'), ]);