Migrations: Use JSON-column and convert it to relation.
Hello everybody,
I got a question: My Laravel-project has used a JSON in the database like this:
$table->json('variants');
Now I created a more sophisticated way to save a model's variants using a relation, which also has the name variants.
Now I'd like to create a migration for this.
My plan is:
Create a migration: php artisan make:migration drop_model_json_row
In the up method, but before Schema::table, create a query to query all model instances and iterate over each result and use the relation to store the variants ($model->variants()->sync($prepared_variant)). Since the row has the same name as the relation, I guess I need to use a raw SQL query?
Now drop the JSON-field in the database
In the down-method, add the JSON-field again, since this is the reversion of the up method
Is this plan valid? Are there good examples out there that show how to handle such "more complex" migrations?
Don’t do the data import with a migration,
Use that to add the new tables suitable for your new table structure.
The down method for this migration would remove the tables you added in your up method - stay away from your jJSON column for now.
Once you have converted the data, then you can add another migration to drop the Json column - you only get one go at that so keep copies of your database so you can rollback if you things go awry.