Part 5: Handling Migrations With Gorm in Go
This is the fifth tutorial in our series building a rest api in golang. In the last tutorial we learnt how one can define models using gorm.
However we did not persist this tables in our database.In this tutorial we are going to persist our tables and also create foreign keys for our tables.Gorm allow us to run migrations very easily.
You can find the code for this tutorial on Github
Open the migrations.go folder that we created in the migrations package and copy the following code.
intializing the migrations
Now what remains is to call our migrate method in our main.go so that we can initialize the migrations.
open the main.go and add the code below.
Note this is a continuation of the previous work from the fourth tutorial so you should add this code to the previous code.
If at this point you run the command go run main.go all the tables should be created in your delivery database.
Any time you make a change to this table the changes will be automatically applied to the database.
WARNING: AutoMigrate will ONLY create tables, missing columns and missing indexes, and WON’T change existing column’s type or delete unused columns to protect your data.
Adding Foreign Keys To Our Database In Gorm
In the last tutorial we discussed about database foreign keys.
In this tutorial we are going to apply them to our database,they will help us to query related data from our database.For example it will be very easy to query users orders once you have foreign keys.
We already defined all related tables in the previous tutorial so what we need to do here is just make sure they are persisted in the database.
Open the migrations.go and add the code below.
With that we are done with our database and we are now ready for action.
Gorm makes it very easy for us to run migrations.However for more complicated migrations you may use gormigrate which we will cover later in this tutorial.
Now we are done with the most important part of our project,that is the database.If you make your database well the other processes will be very easy.
In the next chapter we are going to start making the handlers,that is we are going to start registering users and login in them in our application.We are also going to start adding food.
Make sure to leave a comment of anything you may need more clarification or how we can make this tutorial more helpful to other people who read it.See you in the next tutorial.
Cheers Happy Coding!!!!!