Part 4: Using Gorm Orm To Define Our Models In Golang Rest Api

itachi sasuke
itachi sasuke
i.
Mar 7, 2019 5 min read

This is our fourth tutorial in our series building a rest api with golang.Make sure your have read our previous tutorial Planning Our Project.

You can find the code for this tutorial on Github

In this tutorial we are going to learn how we can define our models using gorm which is a golang orm library.

This will allow us to easily query,update,add and delete data from our postgres database with minimal effort. With gorm making foreign keys and database indexes will also be a very trivial activity.

Making the database connection

To start off make a database called delivery in your postgres this is the database we will be using.

For gorm to be able to access the database we need to make a connection. To avoid circular import we have created a package called database.

Open the database.go and copy the following code.

 0
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
package database
import "github.com/jinzhu/gorm"
var (

	DBCon *gorm.DB


)
func InitDB() {
	var err error

	//connect to postgres database
	DBCon, err = gorm.Open("postgres", "host=localhost port=myport user=gorm dbname=delivery password=mypassword")

	//where myhost is port is the port postgres is running on
	//user is your postgres use name
	//password is your postgres password
	if err != nil {

		panic("failed to connect database")
	}

}

Finally we now need to initialize the database in our main.go file.

Open the main.go and copy the code below.

 0
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package main
import (
	"food-delivery/database"

	_ "github.com/jinzhu/gorm/dialects/postgres"

)
func main() {

	////initialize the database
	database.InitDB()


	///finally close the connection when you are done
	defer database.DBCon.Close()


}

Every thing is now in order we can now connect to our database and query our data.

But One thing is missing in our database,the table to store our data

In gorm tables are defined by use of a models(struct).In the next section we are going to define our models.

Defining Our Models In Gorm.

Now that we already know all the models that we need in our projects let go ahead and make them.

Open the models.go file we created in the third tutorial and copy the code below.

 0
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package models

import "time"

type Food struct {
	//food will contains this fields....
	//we have also defined they type
	ID   int `json:"id,primary_key"` //this will be the primary key field
	Name int `gorm:"size:255"`       ///the name field will only allow a maximum of 255 characters

	OrderItems []OrderItems
	//this defines the relationship between orderitems and food
	//its says that one food can belong to many orderitems and foodId is the foreign_key
	Price     float64
	CreatedAt time.Time
	UpdatedAt time.Time
}

type User struct {
	//this represents the customer
	ID int `json:"id,primary_key"` //this will be the primary key field

	FirstName  string `gorm:"size:255"`
	SecondName string `gorm:"size:255"`

	Orders []Orders
	//this defines the relationship between orders and users
	//its says that one user can have to many orders and UserID is the foreign_key in the order table
	AddressID int
	///address_id is a foreign_key from the address table....
	CreatedAt time.Time
	UpdatedAt time.Time
}

type Orders struct {
	ID int `json:"id,primary_key"` //this will be the primary key field

	OrderItems []OrderItems
	//this defines the relationship between orders and orderitems
	//its says that one order can have  many orderitems and OrderId is the foreign_key in the orderitems table

	UserID    int       `json:"user_id"` ///this is a foreign_key from the user_table
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

type OrderItems struct {
	ID        int       `json:"id,primary_key"` //this will be the primary key field
	OrderId   int                               //this is foreign_key from the  order table
	FoodID    int                               //this is foreign_key from the  food table
	Price     int       `json:"price"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

type Address struct {
	ID   int `json:"id,primary_key"` //this will be the primary key field
	User []User
	//this defines the relationship between users  and Address
	//its says that one address can belong to many users and  is the foreign_key address_id
	AddressName string    `gorm:"size:255"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

Short Explanation

foreign_key-this are used to define the relationship between two tables.For Example a user can have many emails.

If we were to represent this information we would have two tables.One called user tables and another email. In the email table we would have user_id as a foreign key.

table names -the table name will be the pluralized version of our model names. For example the table name for Food will be foods.

You can change this behaviour and provide your own table name.

Nice with that all our models and tables are now ready.

However there is one more thing that we have not done.

That is running our database migration so that we can persist our tables in our postgres database.

In the next tutorial we are going to look at gorm migration and how they are done.

After we will be good to go.

Conclusion

In this tutorial we have learnt the basics of how models are defined using gorm.

As you will learn later you can also define a field that cannot be null.

However this is enough to make a basic go api.

In the next tutorial we are going to learn how you can run migration in golang.

See you in the next tutorial.Happy Coding!!.