by- Kabeer Shaikh
Originally published at RemotePanda Blogs
In Chapter-9 of our Golang Tutorial, we touched upon ‘Go Database/SQL’. In this chapter, let’s explore ‘Go with GORM’.
The GORM is fantastic ORM library for Golang, aims to be developer friendly. It is an ORM library for dealing with relational databases. This Gorm library is developed on the top of database/SQL package.
The overview and feature of ORM are:
- Full-Featured ORM (almost)
- Associations (Has One, Has Many, Belongs To, Many Too Many, Polymorphism)
- Callbacks (Before/After Create/Save/Update/Delete/Find)
- Preloading (eager loading)
- Composite Primary Key
- SQL Builder
- Developer Friendly
To install GORM just use the following command :
go get “github.com/jinzhu/gorm”
In order to use, just import this package into your project along with the database drivers as you want
import ( _ “github.com/go-sql-driver/mysql” “github.com/jinzhu/gorm” _ “github.com/jinzhu/gorm/dialects/mysql” //You could import dialect )
Now use the gorm to do the operations on the database.
In order to connect to the database, just use the following syntax.
DB, err := gorm.Open(“MySQL”, “user:password@/dbname?charset=utf8&parseTime=True&loc=Local”)
NOTE: In order to handle time. Time, you need to use parseTime parameter
Here you have to manually create the database before you connect.
For PostgreSQL, db, err := gorm.Open(“postgres”, “user=gorm dbname=gorm sslmode=disable”)
And remember to close the database when it is not in use using defer defer db.Close()
Creating Models and Tables
Define the models before creating tables and based on the model the table will be created.
This Auto Migration feature will automatically migrate your schema. It will automatically create the table based on your model. We don’t need to create the table manually.
Now just go and check the “ormdemo” database, there you will find the table along with the columns.
Note: You need to create the database manually.
The gorm also has given model definition including fields like Id, CreatedAt, UpdatedAt, DeletedAt. If you want to use just embed gorm.Model in your model/struct.
In the gorm.Model the fields
CreatedAt — used to store records created time
UpdatedAt — used to store records updated time
DeletedAt — used to store records deleted time, It won’t delete the records just set the value of DeletedAt’s field to the current time and you won’t find the record when querying i.e. what we call soft deletion.
If you want to set some SQL parameters to the model fields then you can do like this
Gorm is creating a table with the plural version of the model name like if your model name is UserModel then gorm is creating the tables in its plural version user_models. So in order to avoid this just do db.SingularTable(true).
In gorm, ID field is automatically set to a Primary key field with auto increment property.
The query for the SQL using gorm can be specified like this
In order to create or insert a record, you need to use the Create() function. The save() is also there to that will return the primary key of the inserted record.
In order to update the records in the table using gorm, look into the below sample example.
In order to delete the record from the table, gorm has provided Delete() as given in below examples
In order to fetch the records from the database and do some SQL stuffs gorm has given some query functions. We’ll now do a quick discussion on it.
Now just go through the program
The relationship defines how the structs or models interact with each other. So for this, you need to create/define what kind of relationship at both ends.
One To One Relationship
One to One Relationship specifies how the fields of one models are related with other by specifying one to one mapping. For now, I’ve considered and done one to one mapping between Place and Town struct/model. Here one Town belongs to one Place relational mapping I’ve created.
Note: Here in the example, you need to create the foreign keys manually using add foreign key() function because auto-migration of the foreign key is not happening.
One To Many Relationship
In One to Many relationships, models of two classes are related by specifying one too many mapping. Here in the example, I’ve created the mapping like one customer has many contacts.
Many To Many Relationship
The user belongs to many languages and ‘user_languages’ will be a join table.
Here, you will find the complete documentation about gorm http://jinzhu.me/gorm/
About Kabeer Shaikh:
Kabeer Shaikh is a Android Developer At MindBowser Info Solutions
RemotePanda is a personalized platform for companies to hire remote talent and get the quality work delivered from our city Pune. All talents associated with us are close network connections. When we connect them with you, we make sure to manage their quality, their growth, the legalities and also the delivery of work. The idea is to make remote work successful for you.