当前位置:网站首页>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
边栏推荐
- Use strictmode strictmode principle (1)
- WIN11中MathType编辑中“打开数学输入面板”是灰色不可编辑
- Why not two or four TCP handshakes
- StrictMode分析Activity泄漏-StrictMode原理(3)
- Institute of Microbiology, commonly used biochemical reactions in microbiological testing
- Note d'étude du DC: zéro dans le chapitre officiel - - Aperçu et introduction du processus de base
- Opencv basic operation 2 realizes label2rgb and converts gray-scale images into color images
- 软件开发完整流程
- ASCII、Unicode、GBK、UTF-8之间的关系
- 基础知识之三——标准单元库
猜你喜欢
随机推荐
TypeError: Argument ‘angle‘ can not be treated as a double
visual studio 2019 快捷键备忘
uniapp官方组件点击item无效,解决方案
Why build a personal blog
物业怎么发短信通知给业主?
Openmv and k210 of the f question of the 2021 video game call the openmv API for line patrol, which is completely open source.
【模拟】922. Sort Array By Parity II
None of the following candidates is applicable because of a receiver type mismatch
dc_ Study and summary of labs--lab1
Locking relay ydb-100, 100V
Service grid ASM year end summary: how do end users use the service grid?
Double position relay dls-5/2 dc220v
[问题已处理]-nvidia-smi命令获取不到自身容器的GPU进程和外部的GPU进程号
Use of typora
StrictMode卡顿与泄漏检测-StrictMode原理(2)
3dsmax插件开发遍历节点对象和Object获取及INode变换矩阵说明
Parity linked list [two general directions of linked list operation]
TypeError: can‘t convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to
一些本质的区别
MFC TCP通信服务端客户端Demo备忘vs2019
![Split the linked list [take next first and then cut the linked list to prevent chain breakage]](/img/eb/708ab20c13df75f4dbd2d6461d3602.png)








