æ¾ÂÂÃ¥ÂÂæÂ¥åÂÂå¸Âå¨个人åÂÂ客ãÂÂ
Ã¥ÂÂè¨Âï¼Âä½Â为ORM
è¦Â说ORMæ¯ä½Âç©ï¼ÂæÂÂ们å¾Âå Âä»Âé¢åÂÂ对象è°Âèµ·ãÂÂ
å¨é¢åÂÂ对象çÂÂç¼Âç¨ÂæÂÂæ³ä¸Â贯彻çÂÂä¸Âå¥è¯Âï¼ÂâÂÂä¸ÂÃ¥ÂÂçÂÂ对象ãÂÂâÂÂ
èÂÂå¨æ°æ®åºÂé£边ï¼Â以堳系åÂÂæ°æ®åºÂæ¥说å§ï¼Â堳系åÂÂæ°æ®åºÂÃ¥ÂÂ讲究ï¼ÂâÂÂä¸ÂÃ¥ÂÂå®Âä½Âé½æÂÂ堳系ãÂÂâÂÂ
ä½ åÂÂç°äºÂä»Âä¹Âï¼Â堳系æ¯ä¸Âæ¯ä¹Âè½ç¨对象çÂÂæÂÂæ³åÂȾÂÂè¿°ï¼Â
举个ä¾ÂÃ¥ÂÂï¼ÂÃ¥ÂÂå¦ÂæÂÂä¸Â张表ï¼Â
CREATE TABLE `users` (
`id` integer PRIMARY KEY,
`username` varchar(255),
`role` varchar(255),
`created_at` timestamp
);
å¨è¿Âå¼ åÂÂ为users
çÂÂ表åÂÂ
æÂÂçÂÂ4个åÂÂ段ï¼Âid
,username
,role
Ã¥ÂÂcreated_at
ãÂÂ
Ã¥ÂÂå¦ÂæÂÂ们å°Âå®Âç¨GoçÂÂç»ÂæÂÂä½ÂÃ¥ÂȾÂÂè¿°å¢ï¼Â
type Users struct {
Id int
Username string
Role string
CreatedAt time.Time
}
èªæ¤ï¼ÂæÂÂ们便å®ÂæÂÂäºÂä¸Â个ä»Â表å°ç»ÂæÂÂä½ÂçÂÂæ å°ÂãÂÂ
èÂÂORMÃ¥ÂÂçÂÂ便æ¯è¿Âæ ·ä¸Âç§ÂäºÂæ ï¼Âä»Â表æ å°Âå°对象ãÂÂORM å°±æ¯éÂÂè¿Âå®Âä¾Â对象çÂÂè¯Âæ³Âï¼Âå®ÂæÂÂ堳系åÂÂæ°æ®åºÂçÂÂæÂÂä½ÂçÂÂæÂÂæ¯ï¼Â比对象-堳系æ 尔ï¼ÂObject/Relational Mappingï¼ çÂÂ缩åÂÂãÂÂ
ä¸Âè¾¥说ï¼ÂORMä¼Âå®ÂæÂÂ以ä¸ÂçÂÂæ å°Â堳系ï¼Â
- æ°æ®åºÂçÂÂ表ï¼Âtableï¼ –> ç±»ï¼Âclassï¼Â
- è®°å½Âï¼Ârecordï¼Âè¡Âæ°æ®6> 对象ï¼Âobjectï¼Â
- Ã¥ÂÂ段ï¼Âfield6> 对象çÂÂå±Âæ§ï¼Âattributeï¼Â
å½Âç¶ç±äºÂGo并没æÂÂclass
è¿Â个æ¦Â念ï¼Âå æ¤å¨Goä¸ÂORMä¼Âå®ÂæÂÂ以ä¸ÂçÂÂæ å°ÂÃ¥Â
³ç³»ï¼Â
- æ°æ®åºÂçÂÂ表ï¼Âtableï¼ –> ç»ÂæÂÂä½Âï¼Âstructï¼Â
- è®°å½Âï¼Ârecordï¼Âè¡Âæ°æ®6> ç»ÂæÂÂä½ÂçÂÂå®Âä¾ÂÃ¥ÂÂï¼Âobjectï¼Â
- Ã¥ÂÂ段ï¼Âfield6> ç»ÂæÂÂä½ÂçÂÂÃ¥ÂÂ段ï¼Âfieldsï¼Â
ORMæÂÂçÂÂä¸Âé¢çÂÂä¼Âç¹ï¼Â
- å¼±åÂÂSQLÃ¥ÂÂçÂÂè¯Âå¥çÂÂè¦Âæ±Âï¼Â对äºÂæ°æÂÂæ¥说ç®ÂÃ¥ÂÂæÂÂä½ÂæÂÂä¸ÂæÂÂï¼Â
- å°ÂSQLæ½象æÂÂç»ÂæÂÂä½ÂÃ¥ÂÂ对象ï¼ÂæÂÂäºÂçÂÂ解ï¼Â
- ä¸Âå®Âç¨Â度ä¸Âå¢Âå äºÂå¼ÂÃ¥ÂÂæÂÂçÂÂãÂÂ
ä½Âä¹ÂæÂÂä¸Âå®ÂçÂÂ缺ç¹ï¼Â
- å¢Âå äºÂä¸Âå±Âä¸Âé´ç¯èÂÂï¼ÂÃ¥ÂÂæ¶使ç¨äºÂÃ¥ÂÂå°Âï¼Âçºç²äºÂä¸Âå®ÂçÂÂæ§è½ï¼Â
- çºç²äºÂçµ活æ§ï¼Âå¼±åÂÂäºÂSQLçÂÂè½åÂÂï¼Â
- çºç²äºÂä¸ÂäºÂÃ¥ÂÂçÂÂÃ¥ÂÂè½ãÂÂ
Go çÂÂORMæ¡Âæ¶ï¼ÂGORM
å¨Goä¸Âä¹ÂæÂÂçÂÂè¾Â为æÂÂçÂÂçÂÂORMæ¡Âæ¶ï¼ÂGORMï¼Âå®Âç½Â对å®ÂçÂÂç¹æ§ç®ÂÃ¥ÂÂæÂÂ举äºÂä¸ÂäºÂï¼Â
- å ¨åÂÂè½ ORM
- å ³è (æÂ¥æÂÂä¸Â个ï¼ÂæÂ¥æÂÂå¤Â个ï¼Âå±ÂäºÂï¼Âå¤Â对å¤Âï¼Âå¤ÂæÂÂï¼ÂÃ¥ÂÂ表继æ¿)
- Createï¼ÂSaveï¼ÂUpdateï¼ÂDeleteï¼ÂFind ä¸Âé©åÂÂæ¹æ³Â
- æ¯æ PreloadãÂÂJoins çÂÂé¢Âå 载
- äºÂå¡ï¼ÂåµÂå¥ÂäºÂå¡ï¼ÂSave Pointï¼ÂRollback To to Saved Point
- ContextãÂÂé¢Âç¼Âè¯Â模å¼ÂãÂÂDryRun 模å¼Â
- æ¹éÂÂæÂÂå ¥ï¼ÂFindInBatchesï¼ÂFind/Create with Mapï¼Â使ç¨ SQL 表达å¼ÂãÂÂContext Valuer è¿Âè¡ CRUD
- SQL æÂÂ建å¨ï¼ÂUpsertï¼ÂéÂÂï¼ÂOptimizer/Index/Comment Hintï¼Âå½åÂÂÃ¥ÂÂæ°ï¼ÂÃ¥ÂÂæ¥询
- å¤ÂÃ¥ÂÂ主é®ï¼Âç´¢å¼Âï¼Â约æÂÂ
- èªå¨è¿Â移
- èªå®Âä¹ Logger
- çµ活çÂÂå¯æ©å±ÂæÂÂ件 APIï¼ÂDatabase Resolverï¼Âå¤Âæ°æ®åºÂï¼Â读åÂÂÃ¥ÂÂ离ï¼ÂãÂÂPrometheusâ¦
- æ¯Â个ç¹æ§é½ç»Âè¿ÂäºÂæµÂè¯ÂçÂÂéÂÂéÂÂèÂÂéªÂ
- å¼ÂÃ¥ÂÂè åÂÂ好
让æÂÂ们ç»ÂÃ¥ÂÂä¸Âä¸ÂMySQLç®ÂÃ¥ÂÂä¸ÂæÂÂä¸Âä¸ÂGORMå§ãÂÂ
Ã¥ÂÂæÂÂÃ¥ÂÂå¤Â
ç±äºÂç¬Âè ä¸ÂÃ¥ÂÂ欢ç©çÂÂæºæÂÂMySQLï¼ÂæÂÂ以æ¤å¤Â使ç¨Dockerå¼Âä¸Â个MySQLçÂÂ容å¨ãÂÂ
ç¬Âè 已ç»Âå®Â裠好äºÂDocker å MySQL 客æ·端ï¼Âç°å¨å ÂæÂÂÃ¥ÂÂéÂÂÃ¥ÂÂãÂÂÃ¥ÂÂå¾ÂMySQL çÂÂå®Âæ¹éÂÂÃ¥ÂÂï¼Â
å¨å³侧已ç»ÂÃ¥ÂÂ好äºÂæÂÂÃ¥ÂÂå½令ï¼Âå¤Âå¶ï¼Âå¨æΡç»Â端æ§è¡Âä¸Âä¸Âï¼Â
$ docker pull mysql
Using default tag: latest
latest: Pulling from library/mysql
49bb46380f8c: Pull complete
aab3066bbf8f: Pull complete
d6eef8c26cf9: Pull complete
0e908b1dcba2: Pull complete
480c3912a2fd: Pull complete
264c20cd4449: Pull complete
d7afa4443f21: Pull complete
d32c26cb271e: Pull complete
f1f84a2204cb: Pull complete
9a41fcc5b508: Pull complete
7b8402026abb: Pull complete
Digest: sha256:51c4dc55d3abf4517a5a652794d1f0adb2f2ed1d1bedc847d6132d91cdb2ebbf
Status: Downloaded newer image for mysql:latest
docker.io/library/mysql:latest
æÂÂÃ¥ÂÂå®ÂéÂÂÃ¥ÂÂÃ¥ÂÂæÂÂ们å¯å¨éÂÂÃ¥ÂÂï¼Â
$ docker run --name mysql -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 mysql:latest
824cf9edeaaaf35aeaf58aed5a79c86fa819fd2693f063367b4a5a3404fa8aee
å ¶ä¸Âï¼Â
--name
æ¯容å¨åÂÂÃ¥ÂÂï¼Â-d
代表å¨åÂÂå°è¿Âè¡Âï¼Â-p 3306:3306
代表å°Â容å¨çÂÂ3306端å£æ å°Âå°主æºçÂÂ3306端å£ï¼Â-e
æ¯ç¯å¢ÂÃ¥ÂÂéÂÂï¼Âè¿ÂéÂÂæÂÂä¸Â个ç¯å¢ÂÃ¥ÂÂéÂÂMYSQL_ROOT_PASSWORD
æ¯æÂÂrootç¨æ·çÂÂé»Â认å¯Âç Âï¼Âmysql:latest
代表å¯å¨åÂÂ为mysql
并ä¸Âæ Âç¾为latest
çÂÂéÂÂÃ¥ÂÂãÂÂ
æ¤æ¶æÂÂ们æ¿æΡçÂÂMySQL客æ·端å°Âè¯Âä¸Âä¸Âï¼Â
$ mysql -uroot -p123456
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 8.0.34 MySQL Community Server - GPL
Copyright (c) 2000, 2023, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
æÂÂÃ¥ÂÂè¿ÂæÂ¥ãÂÂ
为äºÂÃ¥ÂÂç»ÂçÂÂæÂÂä½Âï¼ÂæÂÂ们å¨æ¤建ç«Âä¸Â个test
çÂÂæ°æ®åºÂï¼Â
mysql> create database test;
Query OK, 1 row affected (0.10 sec)
Ã¥ÂÂå§ÂÃ¥ÂÂGo项ç®
使ç¨go get -u gorm.io/gorm
为项ç®导åÂ
Â¥GORMæ¡Âæ¶ï¼Â
$ go get -u gorm.io/gorm
go: added github.com/jinzhu/inflection v1.0.0
go: added github.com/jinzhu/now v1.1.5
go: added gorm.io/gorm v1.25.2
Ã¥ÂÂå§ÂÃ¥ÂÂè¿ÂæÂÂ¥
ç±äºÂæÂÂ们使ç¨çÂÂæ¯MySQLï¼Âå æ¤æÂÂ们å Âè¦Âä¸Â载驱å¨ï¼Â
$ go get -u "gorm.io/driver/mysql"
go: added github.com/go-sql-driver/mysql v1.7.1
go: added gorm.io/driver/mysql v1.5.1
ä¸Âè½½å®Â驱å¨åÂÂæÂÂ们便å¯以è¿ÂæÂ¥æ°æ®åºÂäºÂï¼Âæ°建ä¸Â个main.go
ï¼Â
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
const (
user = "root"
password = "123456"
addr = "127.0.0.1:3306"
db = "test"
)
func main() {
dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
user, password, addr, db)
//db 便æ¯æÂÂ们çÂÂæ°æ®åºÂ对象
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
fmt.Println("è¿Âæ¥失败")
}
_ = db
}
å¯以çÂÂå°ï¼ÂGORM æÂÂä¾ÂäºÂgorm.Open
è¿Â个æ¹æ³Â让æÂÂ们å»建ç«Âä¸Â个æ°æ®åºÂçÂÂè¿ÂæÂ¥ï¼ÂèÂÂå¨建ç«Âè¿ÂæÂ¥çÂÂè¿Âç¨Âä¸ÂæÂÂ们ä¹Âå¯以传éÂÂä¸ÂäºÂéÂ
Âç½®æÂ¥éÂ
Âç½®è¿ÂæÂ¥ï¼Âæ¤å¤ÂæÂÂ们传åÂ
¥çÂÂæ¯ä¸Â个空ç»ÂæÂÂä½Âï¼Âå æ¤æÂÂ们没æÂÂä¼ åÂ
¥ä»»ä½ÂéÂ
Âç½®ãÂÂ
func Open(dialector Dialector, opts ...Option) (db *DB, err error)
建ç«Âæ å°Â
Ã¥ÂÂé¢æÂÂ们已ç»Â说è¿ÂäºÂï¼ÂORMæ¡Âæ¶建ç«ÂäºÂè®°å½ÂâÂÂâÂÂç»ÂæÂÂä½ÂçÂÂä¸Â个æ å°Âï¼Âå æ¤æÂÂ们æ¤æ¶就è¦Âå Â建ç«Âä¸Â个ç»ÂæÂÂä½ÂãÂÂ
ä¾Âå¦Âè¿ÂéÂÂæÂÂ们æ°建ä¸Â个user
çÂÂç»ÂæÂÂä½Âï¼Â
type User struct {
gorm.Model
Name string
Age string
}
æ¤å¤ÂçÂÂgorm.Model
æ¯æ¡Âæ¶èª带çÂÂä¸Â个ç»ÂæÂÂä½Âï¼ÂæÂÂä¾ÂäºÂ常è§ÂçÂÂä¸ÂäºÂÃ¥ÂÂ段ï¼Â
type Model struct {
ID uint `gorm:"primarykey"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt DeletedAt `gorm:"index"`
}
æ Âç¾
GORMæ¡Âæ¶æÂÂä¾ÂäºÂÃ¥ÂÂç§ÂÃ¥ÂÂæ ·çÂÂæ Âç¾æ¥为ç»ÂæÂÂä½Â丰å¯Âèª带çÂÂå 容ï¼ÂæÂÂæÂÂçÂÂæ Âç¾类åÂÂå¦Âä¸Âï¼Â
æ Âç¾å | 说æ |
---|---|
column | æÂÂå®Â表çÂÂÃ¥ÂÂå |
type | Ã¥ÂÂæ°æ®类åÂÂï¼Âæ¨èÂÂ使ç¨åÂ
¼å®¹æ§好çÂÂéÂÂç¨类åÂÂï¼Âä¾Âå¦Âï¼ÂæÂÂæÂÂæ°æ®åºÂé½æ¯æ boolãÂÂintãÂÂuintãÂÂfloatãÂÂstringãÂÂtimeãÂÂbytes 并ä¸Âå¯以åÂÂÃ¥Â
¶ä»Âæ Âç¾ä¸Â起使ç¨ï¼Âä¾Âå¦Âï¼Ânot null ãÂÂsize , autoIncrement ⦠å varbinary(8) è¿Âæ ·æÂÂå®Âæ°æ®åºÂæ°æ®类åÂÂä¹Âæ¯æ¯æÂÂçÂÂãÂÂå¨使ç¨æÂÂå®Âæ°æ®åºÂæ°æ®类åÂÂæ¶ï¼Âå®ÂéÂÂè¦Âæ¯å®Âæ´çÂÂæ°æ®åºÂæ°æ®类åÂÂï¼Âå¦Âï¼ÂMEDIUMINT UNSIGNED not NULL AUTO_INCREMENT |
serializer | æÂÂå®Âå°Âæ°æ®åºÂÃ¥ÂÂÃ¥ÂÂæÂÂÃ¥ÂÂåºÂÃ¥ÂÂÃ¥ÂÂå°æ°æ®åºÂä¸ÂçÂÂåºÂÃ¥ÂÂÃ¥ÂÂå¨, ä¾Âå¦Â: serializer:json/gob/unixtime |
size | å®Âä¹ÂÃ¥ÂÂæ°æ®类åÂÂçÂÂ大å°ÂæÂÂé¿度ï¼Âä¾Â妠size: 256 |
primaryKey | å°ÂÃ¥ÂÂå®Âä¹Â为主é® |
unique | å°ÂÃ¥ÂÂå®Âä¹Â为å¯ä¸Âé® |
default | å®Âä¹ÂÃ¥ÂÂçÂÂé»Â认å¼ |
precision | æÂÂå®ÂÃ¥ÂÂçÂÂ精度 |
scale | æÂÂå®ÂÃ¥ÂÂ大尠|
not null | æÂÂå®ÂÃ¥ÂÂ为 NOT NULL |
autoIncrement | æÂÂå®ÂÃ¥ÂÂ为èªå¨å¢Âé¿ |
autoIncrementIncrement | èªå¨æÂ¥é¿ï¼Âæ§å¶è¿Âç»Âè®°å½Âä¹Âé´çÂÂé´é |
embedded | åµÂå¥ÂÃ¥ÂÂ段 |
embeddedPrefix | åµÂå ¥åÂÂ段çÂÂÃ¥ÂÂÃ¥ÂÂÃ¥ÂÂç¼ |
autoCreateTime | Ã¥ÂÂ建æ¶追踪å½ÂÃ¥ÂÂæ¶é´ï¼Â对亠int Ã¥ÂÂ段ï¼Âå®Âä¼Â追踪æ¶é´æ³ç§Âæ°ï¼Âæ¨å¯以使ç¨ nano /milli æ¥追踪纳ç§ÂãÂÂ毫ç§Âæ¶é´æ³ï¼Âä¾Âå¦Âï¼ÂautoCreateTime:nano |
autoUpdateTime | Ã¥ÂÂ建/æ´æ°æ¶追踪å½ÂÃ¥ÂÂæ¶é´ï¼Â对亠int Ã¥ÂÂ段ï¼Âå®Âä¼Â追踪æ¶é´æ³ç§Âæ°ï¼Âæ¨å¯以使ç¨ nano /milli æ¥追踪纳ç§ÂãÂÂ毫ç§Âæ¶é´æ³ï¼Âä¾Âå¦Âï¼ÂautoUpdateTime:milli |
index | æ ¹æ®åÂÂæ°åÂÂ建索å¼Âï¼Âå¤Â个åÂÂ段使ç¨ç¸åÂÂçÂÂÃ¥ÂÂ称åÂÂÃ¥ÂÂ建å¤ÂÃ¥ÂÂç´¢å¼Âï¼ÂæÂ¥ç 索张è·åÂÂ详æ |
uniqueIndex | 丠index ç¸åÂÂï¼Âä½ÂÃ¥ÂÂ建çÂÂæ¯å¯ä¸Â索张|
check | Ã¥ÂÂ建æ£Âæ¥约æÂÂï¼Âä¾Â妠check:age > 13 ï¼ÂæÂ¥ç 约æ è·åÂÂ详æÂÂ
|
<- | 设置åÂÂ段åÂÂÃ¥Â
¥çÂÂæÂÂéÂÂï¼ <-:create åªåÂÂ建ãÂÂ<-:update åªæ´æ°ãÂÂ<-:false æ åÂÂÃ¥Â
¥æÂÂéÂÂãÂÂ<- Ã¥ÂÂ建åÂÂæ´æ°æÂÂé |
-> | 设置åÂÂ段读çÂÂæÂÂéÂÂï¼Â->:false æ 读æÂÂé |
– | 忽ç¥该åÂÂ段ï¼Â- 表示æ 读åÂÂï¼Â-:migration 表示æ è¿Â移æÂÂéÂÂï¼Â-:all 表示æ 读åÂÂè¿Â移æÂÂé |
comment | è¿Â移æ¶为åÂÂ段添å 注é |
èªå¨è¿Â移
å½ÂæÂÂ们çÂÂç»ÂæÂÂä½Âæ´æ°äºÂï¼Âä½Âæ¯表没æÂÂæ´æ°ï¼Â
æÂÂè å½ÂæÂÂ们åÂÂ好äºÂç»ÂæÂÂä½Âä½Âæ¯没æÂÂÃ¥ÂÂ建表ï¼Â
æÂÂ们å¯以éÂÂè¿ÂGORMæÂÂä¾ÂçÂÂèªå¨è¿Â移åÂÂè½æ¥解å³ä¸Âé¢çÂÂé®é¢ÂãÂÂ
å¨GORMä¸Âï¼ÂæÂÂ们å¯以æÂÂç §è¿Âæ ·çÂÂæ¹å¼ÂæÂ¥èªå¨è¿Â移ï¼Â
type User struct {
gorm.Model
Name string
Age string
}
func main() {
dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
user, password, addr, db)
//db 便æ¯æÂÂ们çÂÂæ°æ®åºÂ对象
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
fmt.Println("è¿Âæ¥失败")
}
err = db.AutoMigrate(&User{})
if err != nil {
fmt.Println("èªå¨è¿Â移失败")
}
}
æ§è¡Âç¨ÂåºÂï¼Âç¶åÂÂæÂ¥çÂÂä¸Âä¸Âæ°æ®åºÂæ¤æ¶çÂÂæ åÂ括Â
mysql> SHOW FULL TABLES;
+----------------+------------+
| Tables_in_test | Table_type |
+----------------+------------+
| users | BASE TABLE |
+----------------+------------+
1 row in set (0.01 sec)
mysql> DESCRIBE users;
+------------+-----------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+-----------------+------+-----+---------+----------------+
| id | bigint unsigned | NO | PRI | NULL | auto_increment |
| created_at | datetime(3) | YES | | NULL | |
| updated_at | datetime(3) | YES | | NULL | |
| deleted_at | datetime(3) | YES | MUL | NULL | |
| name | longtext | YES | | NULL | |
| age | longtext | YES | | NULL | |
+------------+-----------------+------+-----+---------+----------------+
6 rows in set (0.02 sec)
Ã¥ÂÂå¦Âæ¤æ¶æÂÂ们æ´æ¹ä¸Âä¸Âuser
ç»ÂæÂÂä½Âï¼Â
type User struct {
gorm.Model
Name string
Age string
NickName string
}
Ã¥ÂÂ次è¿Âè¡ÂÃ¥ÂÂæÂÂ们æÂ¥çÂÂä¸Âä¸Â表ç»ÂæÂÂï¼Â
mysql> DESCRIBE users;
+------------+-----------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+-----------------+------+-----+---------+----------------+
| id | bigint unsigned | NO | PRI | NULL | auto_increment |
| created_at | datetime(3) | YES | | NULL | |
| updated_at | datetime(3) | YES | | NULL | |
| deleted_at | datetime(3) | YES | MUL | NULL | |
| name | longtext | YES | | NULL | |
| age | longtext | YES | | NULL | |
| nick_name | longtext | YES | | NULL | |
+------------+-----------------+------+-----+---------+----------------+
7 rows in set (0.00 sec)
CRUD
å½ÂæÂÂ们建ç«Â好è¿ÂæÂ¥åÂÂå°±è¦Âå¼Âå§Âå¢Âå æ¹æÂ¥äºÂãÂÂ
CreateâÂÂâÂÂå¢Â
å¨GORMä¸Âï¼Âæ¡Âæ¶æÂÂä¾ÂäºÂCreate()
æ¹æ³ÂæÂ¥æ°建ä¸Âæ¡记å½Âï¼Â
user := User{
Name: "Nick",
Age: "19",
NickName: "AAA",
}
result := db.Create(&user)
//å¦ÂæÂÂæ³è¦Âå¤æÂÂÃ¥ÂÂ建ç»ÂæÂÂæ¯å¦æÂÂÃ¥ÂÂï¼ÂåªéÂÂè¦Âè°Âç¨result.Errorå³å¯
if result.Error != nil {
fmt.Println("Ã¥ÂÂ建失败")
}
//è¿ÂÃ¥ÂÂè®°å½ÂçÂÂID
fmt.Println("Id = ", user.ID)
//è¿ÂÃ¥ÂÂæÂÂÃ¥Â
¥è®°å½ÂçÂÂæ¡æ°
fmt.Println("Rows = ", result.RowsAffected)
è¿Âè¡ÂÃ¥ÂÂæÂÂ们æ¤æ¶æÂ¥çÂÂ表ï¼Â
mysql> SELECT * FROM users;
+----+-------------------------+-------------------------+------------+------+------+-----------+
| id | created_at | updated_at | deleted_at | name | age | nick_name |
+----+-------------------------+-------------------------+------------+------+------+-----------+
| 1 | 2023-07-28 19:29:18.168 | 2023-07-28 19:29:18.168 | NULL | Nick | 19 | AAA |
+----+-------------------------+-------------------------+------------+------+------+-----------+
1 row in set (0.00 sec)
å½Âç¶你ä¹Âå¯以éÂÂè¿Âä¼ å ¥ä¸Â个åÂÂçÂÂçÂÂæ¹å¼ÂæÂ¥æ¹éÂÂå¢Âå 记å½Âï¼Â
users := []*User{
&User{
Name: "A",
Age: "15",
NickName: "a",
},
&User{
Name: "B",
Age: "16",
NickName: "b",
},
}
result := db.Create(&users)
//å¦ÂæÂÂæ³è¦Âå¤æÂÂÃ¥ÂÂ建ç»ÂæÂÂæ¯å¦æÂÂÃ¥ÂÂï¼ÂåªéÂÂè¦Âè°Âç¨result.Errorå³å¯
if result.Error != nil {
fmt.Println("Ã¥ÂÂ建失败")
}
//è¿ÂÃ¥ÂÂæÂÂÃ¥Â
¥è®°å½ÂçÂÂæ¡æ°
fmt.Println("Rows = ", result.RowsAffected)
è¿Âè¡ÂÃ¥ÂÂæÂ¥çÂÂÃ¥ÂÂ表ï¼Â
mysql> SELECT * FROM users;
+----+-------------------------+-------------------------+------------+------+------+-----------+
| id | created_at | updated_at | deleted_at | name | age | nick_name |
+----+-------------------------+-------------------------+------------+------+------+-----------+
| 1 | 2023-07-28 19:29:18.168 | 2023-07-28 19:29:18.168 | NULL | Nick | 19 | AAA |
| 2 | 2023-07-28 19:33:38.961 | 2023-07-28 19:33:38.961 | NULL | A | 15 | a |
| 3 | 2023-07-28 19:33:38.961 | 2023-07-28 19:33:38.961 | NULL | B | 16 | b |
+----+-------------------------+-------------------------+------------+------+------+-----------+
3 rows in set (0.00 sec)
ReadâÂÂâÂÂæÂÂ¥
GORM æÂÂä¾Â亠First
ãÂÂTake
ãÂÂLast
æ¹æ³Âï¼Â以便ä»Âæ°æ®åºÂä¸Âæ£Âç´¢åÂÂ个对象ãÂÂå½Âæ¥询æ°æ®åºÂæ¶å®Âæ·»å 亠LIMIT 1
æ¡件ï¼Âä¸Â没æÂÂæ¾å°记å½Âæ¶ï¼Âå®Âä¼Âè¿Âå ErrRecordNotFound
éÂÂ误
user := User{}
// è·åÂÂ第ä¸Âæ¡记å½Âï¼Â主é®åÂÂåºÂï¼Â
db.First(&user)
// SELECT * FROM users ORDER BY id LIMIT 1;
fmt.Println(user)
// è·åÂÂä¸Âæ¡记å½Âï¼Â没æÂÂæÂÂå®ÂæÂÂåºÂÃ¥ÂÂ段
db.Take(&user)
// SELECT * FROM users LIMIT 1;
fmt.Println(user)
// è·åÂÂæÂÂÃ¥ÂÂä¸Âæ¡记å½Âï¼Â主é®éÂÂåºÂï¼Â
db.Last(&user)
// SELECT * FROM users ORDER BY id DESC LIMIT 1;
fmt.Println(user)
result := db.First(&user)
fmt.Println(result.RowsAffected) // è¿ÂÃ¥ÂÂæ¾å°çÂÂè®°å½Âæ°
if result.Error != nil { // returns error or nil
fmt.Println(result.Error)
}
// æ£ÂæÂÂ¥ ErrRecordNotFound éÂÂ误
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
fmt.Println("æ¾ä¸Âå°记å½Â")
}
WHERE
å¨GORMä¸Âï¼Âä¹ÂæÂÂä¾ÂäºÂÃ¥ÂÂSQL类似çÂÂWHERE
æ¹æ³ÂæÂ¥è¿Â滤æÂÂ们çÂÂæ¥询ç»ÂæÂÂãÂÂ并ä¸Âå¨WHEREÃ¥ÂÂ
çÂÂæ¥询è¯Âå¥æ¯åÂÂSQLçÂÂè¯Âæ³Âåºæ¬ä¸Âè´çÂÂãÂÂ
// Get first matched record
db.Where("name = ?", "Nick").First(&user)
// SELECT * FROM users WHERE name = 'jinzhu' ORDER BY id LIMIT 1;
// Get all matched records
db.Where("name <> ?", "A").Find(&users)
// SELECT * FROM users WHERE name <> 'jinzhu';
// IN
db.Where("name IN ?", []string{"A", "B"}).Find(&users)
// SELECT * FROM users WHERE name IN ('jinzhu','jinzhu 2');
// LIKE
db.Where("name LIKE ?", "%Ni%").Find(&users)
// SELECT * FROM users WHERE name LIKE '%jin%';
// AND
db.Where("name = ? AND age >= ?", "Nick", "10").Find(&users)
// SELECT * FROM users WHERE name = 'jinzhu' AND age >= 22;
// BETWEEN
db.Where("age BETWEEN ? AND ?", "5", "15").Find(&users)
// SELECT * FROM users WHERE age BETWEEN '5' AND '15';
UpdateâÂÂâÂÂæ¹
å½ÂæÂÂ们éÂÂè¿Âæ¥询æ¹æ³Âæ¿å°记å½ÂÃ¥ÂÂï¼ÂæÂÂ们å¯以æ´æ¹è¿Â个ç»ÂæÂÂä½ÂæÂ¥æ´æ¹记å½Âï¼ÂèÂÂÃ¥ÂÂ使ç¨Save
æ¹æ³ÂæÂ¥æ´æ°åÂÂ段ï¼Â
user := User{}
db.First(&user)
//æ¿å°记å½ÂÃ¥ÂÂæÂÂ们ç´æÂ¥æ´æ¹记å½Âå³å¯
user.Name = "Luna"
db.Save(&user)
//æÂÂä¸Â个ç¹æ§ï¼Âå¦ÂæÂÂä½ ä¼ åÂ
¥çÂÂç»ÂæÂÂä½ÂÃ¥ÂÂ
没æÂÂÃ¥ÂÂ
å«主é®çÂÂè¯Âï¼Âé£ä¹Âæ¤æ¶Saveä¼Âè°Âç¨Createæ¹æ³Â
userWithoutId := User{
Name: "123",
}
//è¿ÂéÂÂ便æ¯Createæ¹æ³Âï¼Âç¸å½ÂäºÂSQLçÂÂINSERT
db.Save(&userWithoutId)
userWithId := User{Model: gorm.Model{ID: 1}, Name: "s"}
//è¿ÂéÂÂ便æ¯Saveæ¹æ³Âï¼Âç¸å½ÂäºÂSQLçÂÂUPDATE
db.Save(&userWithId)
DELETEâÂÂâÂÂÃ¥ÂÂ
é¦Âå Âç¡®å®Â两个æ¦Â念ï¼Â
- 软å é¤ï¼ÂéÂÂè¿Âç¹å®ÂçÂÂæ Âè®°æ¹å¼Âå¨æ¥询çÂÂæ¶åÂÂå°Âæ¤记å½Âè¿Â滤æÂÂãÂÂè½ç¶æ°æ®å¨çÂÂé¢ä¸Âå·²ç»ÂçÂÂä¸Âè§Âï¼Âä½Âæ¯æ°æ®åºÂè¿Âæ¯åÂÂå¨çÂÂãÂÂ
- 硬å é¤ï¼Âä¼ ç»ÂçÂÂç©çÂÂå é¤ï¼Âç´æÂ¥å°Â该记å½Âä»Âæ°æ®åºÂä¸Âå é¤ãÂÂ
为ä»Âä¹Âå¼Âå ¥è¿Â两个æ¦Â念ï¼Âè¿ÂéÂÂçÂÂç»Â读è èªè¡ÂæÂÂèÂÂãÂÂ
å¨GORMä¸Âä¹ÂæÂÂçÂÂå é¤çÂÂæ¹æ³Âï¼ÂDelete
:
user := User{
Age: "16",
}
db.Delete(&user)
// DELETE from users where age = '16';
db.Where("name = ?", "s").Delete(&user)
// DELETE from users where name = 's' and age = '16';
注æÂÂçÂÂæ¶ï¼Âç±äºÂæÂÂ们没æÂÂæÂÂå®Â主é®ï¼Âå æ¤GORMä¼Âå é¤ä¸ÂÃ¥ÂÂ符åÂÂçÂÂéÂÂæ¡件çÂÂè®°å½ÂãÂÂ
å¦ÂæÂÂæÂÂ们根æ®主é®å é¤ï¼Â
db.Delete(&user, 1)
// DELETE from users where id = 1 and age = '16';
db.Delete(&user, []int{1, 2, 3})
// DELETE from users where id in (1,2,3) and age = '16';
软å é¤åÂÂ硬å é¤
GORMä¸Âï¼Âå½Âä½ çÂÂç»ÂæÂÂä½Âæº带æÂÂgorm.DeletedAt
Ã¥ÂÂ段æ¶ï¼Âæ¤æ¶GORMå°Âä¸Âä¼Âç´æÂ¥å é¤记å½Âï¼ÂèÂÂæ¯ä¼Âå°Âè¿Â个åÂÂ段çÂÂå¼æ´æ°为å½ÂÃ¥ÂÂæ¶é´ï¼ÂÃ¥ÂÂ使ç¨GORMçÂÂæ¥询æ¶ä¸Â辯æ æ³Âæ¥询å°该记å½ÂçÂÂãÂÂä½Âä½ å¯以使ç¨Unscoped
æÂ¥æ¥询å°被软å é¤çÂÂè®°å½ÂãÂÂ
var users []User
db.Unscoped().Where("age = '16'").Find(&users)
// SELECT * FROM users WHERE age = '16';
ä½ ä¹Âå¯以使ç¨ Unscoped
æ¥永ä¹Â
å é¤å¹éÂ
ÂçÂÂè®°å½Â
db.Unscoped().Delete(&user)
// DELETE FROM users WHERE age = '16';
æ»ç»Â
GORM ä½Â为Go æ¯Âè¾ÂæÂÂçÂÂçÂÂORM æ¡Âæ¶ï¼Âå®ÂçÂÂä¸Âå¡è½åÂÂæ¯æÂÂç®報ç¹çÂÂãÂÂ对äºÂæ°æÂÂèÂÂè¨Âï¼ÂèÂ¥è¦Âå¿«éÂÂå¦习ä¸ÂSQLçÂÂ交äºÂï¼Âä»ÂGORMå ¥æÂÂä¹Â许æ¯ä¸Â个ä¸ÂéÂÂçÂÂéÂÂæ©ãÂÂ
Ã¥ÂÂæ¶GORMè¿ÂæÂÂçÂÂæ´å¤Â好ç©çÂÂç¹æ§ï¼Âä¸Âç¯ÂæÂÂç« ç¬Âè å°Âå°Âè¯Â讲解å°ÂGinÃ¥ÂÂGormç»ÂÃ¥ÂÂèµ·æÂ¥çÂÂå®Âé åºÂç¨ãÂÂ
æ¾ÂÂ示ä¾Â代ç Âå·²æ¾å¨ä»ÂåºÂÃ¥ÂÂ