“This is the 9th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

preface

I started the basic Gin framework jungle to implement an interface function. Today I will use GROM briefly

What is the ORM

Object-relationl Mapping, Relationl refers to the relational database, the most common relational database is Mysql, this will take Mysql to do an experiment, ORM encapsulates the database access details, use the code to express database represented as objects, the ORM encapsulate database operations, allows developers to manipulate, the data objects don’t need to care about the underlying database principle, write to add and delete time can reduce the workload, but we will still use native complex statements statements that are easier to understand and maintain, So using ORM is very popular now.

Install Gorm

Use the following command to install two third-party dependencies in the project root directory:

go mod get  github.com/jinzhu/gorm
go  get github.com/jinzhu/gorm/dialects/mysql
Copy the code

Realize the function

Implementation of the implementation of the function, in the code below the point

Mainly completed the automatic migration of database structure, an interface to query all categories, all categories below all urls, that is, ORM list data:

code

In order to show the convenience, write in a file, so a little long, but the basic function, can use the line, ha ha ~ later have energy can sort it out.

package main import ( "fmt" "github.com/gin-gonic/gin" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" ) var db *gorm.DB type UrlType struct { ID uint `gorm:"primary_key"` Name string  UrlLists []UrlList `gorm:"FOREIGNKEY:TypeID; ASSOCIATION_FOREIGNKEY:ID" '} type UrlList struct {ID uint 'gorm:"primary_key"' TypeID uint // Default foreign key, User Id Name String URL string} func init() {// Create a connection to the database var err Error MyUser := "*****" Password := "**************" Host := "***.***.***.***" Port := 3306 Db := "******" connArgs := fmt.Sprintf("%s:%s@(%s:%d)/%s? charset=utf8&parseTime=True&loc=Local", MyUser, Password, Host, Port, Db) db, err = gorm.Open("mysql", connArgs) if err ! = nil {panic(err)} db.singularTable (true) // Remove s db.automigrate (&UrlList{}, &urlType {}) // Automatic transfer} func main() {r := gin.Default() r.et ("/ping", func(c *gin.Context) {c.son (200, gin.H{ "message": "pong", }) }) defer db.Close() r.GET("/index", func(c *gin.Context) { var list []UrlType db.Debug().Preload("UrlLists").Find(&list) c.JSON(200, gin.H{ "message": list, }) }) r.Run() }Copy the code

The main points of

Introducing packet principle

Two packages were downloaded. One is GORM, one is mysql, and when you import a mysql package there’s an underscore in front of it which means that when you import a mysql package you don’t import the whole package but you call init init in the package. Gorm is imported directly, and a lot of the methods of this package are used in this single file.

GORM field definition

A category has a lot of tabular data. A FOREIGNKEY constraint is used, ASSOCIATION_FOREIGNKEY is used to display the specified FOREIGNKEY relationship, and typeids are forced to look up the list with the classified primary key ID. UrlLists this field is a specified relationship and will not generate fields in the database. The function is to display its subordinate associated data in the query.

The query

db.Debug().Preload("UrlLists").Find(&list)
Copy the code

Prelad mean preloading the meaning of this sentence is to find all the first classification data, using the classification analysis of the correlation ID query its classification data, the following list can be understood as the original query:

SELECT * FROM url_type; SELECT * FROM url_list WHERE type_id IN (1,2,3...) ;Copy the code

conclusion

It’s rough, but it still does what you want. Let’s optimize the details of this framework, or try deploying this simple framework into a real environment using Docker.