当前位置:网站首页>gin_ gorm
gin_ gorm
2022-07-01 01:31:00 【weixin_ thirty-eight million one hundred and seven thousand fou】
One 、 Use form
1、 introduce gorm package
import "github.com/jinzhu/gorm"2、 Import database driver
import _ "github.com/go-sql-driver/mysql"
For convenience, remember the import path ,GORM Packed some drives :
import _ "github.com/jinzhu/gorm/dialects/mysql"
// import _ "github.com/jinzhu/gorm/dialects/postgres"
// import _ "github.com/jinzhu/gorm/dialects/sqlite"
// import _ "github.com/jinzhu/gorm/dialects/mssql"
So it can be used in the following two forms mysql:
1、
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
2、
import (
"github.com/jinzhu/gorm"
_ "github.com/go-sql-driver/mysql"
)
3、 Connect to database
// Connect to database
user name : password @tcp(ip:port)/ database ?charset=utf8&parseTime=True&loc=Local
db, err := gorm.Open("mysql", "root:[email protected](localhost:3306)/go_project?charset=utf8&parseTime=True&loc=Local")
if err != nil {
panic(err)
}
defer db.Close() // Close idle connections 4.DDL operation
type User struct {
Id int
Name string
Age int
}
// Create table
db.Table("user").CreateTable(&User{}) // Specified table name
db.CreateTable(&User{}) // Do not specify a table name , The model will be followed by sDML operation
// 1. increase
//db.Create(&models.User{Name: " Li Si ", Age: 18, Addr: "xxx", Pic: "/static/upload/pic.png", Phone: "123456789"})
// Inquire about
var user models.User
//db.First(&user, 1) // Default id
//db.First(&user, "name=?", " Zhang San ") // // Specified field
//fmt.Println(user)
// to update
//db.First(&user, 1)
//db.Model(&user).Update("age", 22)
//db.Model(&user).Update("addr", "zs-xxxx")
// Delete
db.First(&user, 2)
db.Delete(&user)Model definition
Used for database data conversion and automatic table creation
Mapping relationship between model name and table name
- The rules
- The first capital letter becomes lowercase ,
- Encounter other uppercase letters that become lowercase and preceded by an underscore ,
- Several capital letters connected , Only the first one follows the above two rules , Other uppercase letters are converted to lowercase , No underline , Lowercase encountered , The first uppercase letter in front becomes lowercase and underlined
- Plural form
- give an example
- User --> users Initial lowercase , The plural
- UserInfo --> user_infos
- DBUserInfo --> db_user_infos
- DBXXXXUserInfo --> dbxxxx_user_infos
Add other rules to the default table name
// Add sys_ Prefix
gorm.DefaultTableNameHandler = func (db *gorm.DB, defaultTableName string) string {
return "sys_" + defaultTableName;
}
Custom table name :
func ( Model ) TableName() string{
return " New table name "
}
package models
import "github.com/jinzhu/gorm"
type GormModel struct {
gorm.Model
Name string
}
func (GormModel) TableName() string {
return "test_gorm_model"
}Rules for the correspondence between structure field names and column names
- The rules * The column name is the serpentine lowercase of the field name
- give an example
- Name --> name
- CreatedTime --> create_time
- Can pass gorm Label specifies the column name ,AnimalId int64 `gorm:"column:beast_id"`
gorm.Model
Basic model definition gorm.Model, Including field ID,CreatedAt,UpdatedAt,DeletedAt
You just need to specify... In your own model gorm.Model Anonymous field , You can use the four fields above
// Add fields `ID`, `CreatedAt`, `UpdatedAt`, `DeletedAt`
type User struct {
gorm.Model
Name string
}ID: The primary key grows by itself
CreatedAt: Used to store the creation time of the record
UpdatedAt: The modification time used to store the record
DeletedAt: Delete time used to store records
Structural tag gorm Use
type UserInfo struct {
Id int `gorm:"primary_key"`
Name string `gorm:"index"`
Age int
}gorm Tag attribute value
- -: Ignore , Do not map this field `gorm:"-"`
- primary_key: Primary key `gorm:"primary_key"`
- AUTO_INCREMENT: Self increasing `gorm:"AUTO_INCREMENT"`
- not null: Not empty , The default is empty. `gorm:"not null"`
- index: Indexes , `gorm:"index"`
- Create an index and name : `gorm:"index:idx_name_code"`
- Optimized query , The equivalent of a catalogue of books
unique_index: unique index `gorm:"unique_index"`
unique: only `gorm:"unique"`
column: Specifies the column name `gorm:"column:user_name"`
size: String length , The default is 255 `gorm:"size:64"`
- type: Set up sql type `gorm:"type:varchar(100)"` // It is not recommended to change the type directly
- default `default:'galeone'` The default value is
Multiple attribute values are separated by semicolons ( In English, ;):`gorm:"size:64;not null"`
one-on-one
package relate_tables
// one-on-one
type User struct {
Id int
Name string
Age int
Addr string
}
type UserProfile struct {
Id int
Pic string
CPic string
Phone string
User User // Connections
UserID int
}


// one-on-one
// Belong to
type User struct {
Id int
Name string
Age int
Addr string
}
type UserProfile struct {
Id int
Pic string
CPic string
Phone string
//User User // Connections
User User `gorm:"ForeignKey:UId;AssociationForeignKey:Id"` // Connections
//UserID int // Default associated fields
UId int //uid
}

contain
// contain
type User struct {
Id int
Name string
Age int
Addr string
PId int
}
type UserProfile struct {
Id int
Pic string
CPic string
Phone string
User User `gorm:"ForeignKey:PId;AssociationForeignKey:Id"` // Connections
}

One to many
// One to many
type User2 struct {
Id int
Name string
Age int
Addr string
Articles []Article `gorm:"ForeignKey:UId;AssociationForeignKey:Id"`
}
type Article struct {
Id int
Title string
Content string
Desc string
// Foreign keys
UId int
}


Many to many
type Article2 struct {
AId int `gorm:"primary_key:true"`
Title string
Content string
Desc string
Tags []Tag `gorm:"many2many:Article2s2Tags"` // ;ForeignKey:AId;AssociationForeignKey:TId
}
type Tag struct {
TId int `gorm:"primary_key:true"`
Name string
Desc string
} 


One on one operation
边栏推荐
- 微研所,微生物检验中常用的生化反应
- Install redis database and download redis Desktop Manager in win11
- Pytorch programming knowledge (2)
- K210 site helmet
- 1175. Prime Arrangements
- Koa koa combine routes sub route management
- Exploring the road of steam education innovation in the Internet Era
- visual studio 2019 下载
- Locking relay ydb-100, 100V
- TypeError: can‘t convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to
猜你喜欢

用recyclerReview展示Banner,很简单

Institute of Microbiology, commonly used biochemical reactions in microbiological testing

Xjy-220/43ac220v static signal relay

Introduction and principle analysis of cluster and LVS

Microbiological health, why is food microbiological testing important

One of the basics - overview of sta Basics

Install redis database and download redis Desktop Manager in win11

农产品换房?“变相”购房补贴!

Installing mongodb database in Windows Environment

New opportunities for vr/ar brought by metauniverse
随机推荐
Poor students can also play raspberry pie
用recyclerReview展示Banner,很简单
gin_gorm
生意和投资的思考
Microbiological health, why is food microbiological testing important
微研所,微生物检验中常用的生化反应
About vctk datasets
流批一体在京东的探索与实践
[deepin] common sets
About the general input operation mode of unity
Using recyclerreview to show banner is very simple
Document service design
Why build a personal blog
农产品换房?“变相”购房补贴!
Construction and beautification of personal blog
Strictmode analysis activity leakage -strictmode principle (3)
ESP8266 RC522
数字IC设计流程总结
迪赛智慧数——其他图表(平行坐标图):2021年应届专业就业情况
Relationship between ASCII, Unicode, GBK, UTF-8