Hi, I have a situation where I need to change the schema for an established Laravel app. I'm removing a model called 'customer' and all its relationships etc. Part of this work is to duplicate an existing column that references another, and then delete it. So I have this migration:
Schema::table('tableone', function (Blueprint $table) {
$table->bigInteger('user_id')->unsigned()->after('mid');
$table->string('customer_surname', 50)->nullable()->after('user_id');
$table->string('customer_forename', 20)->nullable()->after('user_id');
$table->string('customer_title', 20)->nullable()->after('user_id');
});
DB::statement('UPDATE tableone
INNER JOIN customers ON tableone.customer_id = customers.id
SET
tableone.user_id = customers.user_id,
tableone.customer_title = customers.title,
tableone.customer_forename = customers.forename,
tableone.customer_surname = customers.surname');
Schema::table('tableone', function (Blueprint $table) {
$table->foreign('user_id')->references('id')->on('users');
$table->dropForeign('tableone_customer_id_foreign');
$table->dropColumn('customer_id');
});
As you can see, I'm creating a new column called user_id, using the DB::statement to populate it with data from the existing customer_id column, then adding a foreign key for user_id and dropping customer_id.
If I don't run the update query, this would work fine on fresh installs, but barfs with a "foreign key constraint" failure when run on a full DB.
So... this works but seems kinda fishy to me - changing data in a Migration. Is there a better away to do this? Should the UPDATE be in a seeder and if so, how do I make sure that seeder is run at the right point when deploying this?
Open to ideas and all related criticism thanks!