当前位置:网站首页>Golang quickly generates model and queryset of database tables
Golang quickly generates model and queryset of database tables
2022-07-02 14:07:00 【It workers】
It's generation model The directory xxx.go and xxx_gen.go file
Tools used :
Quickly generate model:gentool
according to model Generate queryset:go-queryset
Here are the detailed steps .
summary
Golang When operating database tables , You may often need to create a corresponding data table as shown in the following figure struct object , Is often referred to as model, Some of you might say ,model There are few fields , Just write it by hand , There is no need to use tools to generate . When there are fewer database tables , And when there are few fields in the table, it can be done by hand , But if you need to generate model There are many tables in , Every model There are also many fields , At this time, it may be a more appropriate choice to use tools to generate , It's also less likely to make mistakes . So here's an example of how to quickly generate model Document and queryset Methods .
Install and download first gentool Tools
go install gorm.io/gen/tools/[email protected]
Execute the following command to generate... Corresponding to the data table model file , For the usage of the command, refer to the following “ Case presentation ”.
gentool -dsn "user:[email protected](127.0.0.1:3306)/database?charset=utf8mb4&parseTime=True&loc=Local" -tables "student" -onlyModel
Case presentation
1、 Generate model file
For example, I want to give student Table to generate model ,student The table has the following fields .
CREATE TABLE `student`(
`id` BIGINT(20) UNSIGNED not NULL AUTO_INCREMENT COMMENT ' Self increasing id',
`school_id` BIGINT(20) NOT NULL DEFAULT '0' COMMENT ' Student number ',
`name` VARCHAR(64) NOT NULL DEFAULT '0' COMMENT ' full name ',
`male` TINYINT(4) NOT NULL DEFAULT '0' COMMENT ' Gender ',
`phone_number` BIGINT(20) NOT NULL DEFAULT '0' COMMENT ' cell-phone number ',
`addr` VARCHAR(255) NOT NULL DEFAULT '' COMMENT ' Home address ',
`class` VARCHAR(255) NOT NULL DEFAULT '0' COMMENT ' class ',
`major` INT NOT NULL DEFAULT '0' COMMENT ' major id',
`grade` INT NOT NULL DEFAULT '0' COMMENT ' Year of enrollment / grade ',
`extra` text NOT NULL DEFAULT '' COMMENT ' other ',
`create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ' Creation time ',
`modify_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ' Update time ',
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COMMENT=' Student basic information table ';Use the following command to generate model,model The file will be generated one level above the current path called model In the folder of , For example demo/aaa Execute the above command under , that model Will be generated in demo/model Under the path , If model If the path does not exist, it will be created automatically .
gentool -dsn "root:[email protected](127.0.0.1:3306)/my_test_db?charset=utf8mb4&parseTime=True&loc=Local" -tables "student" -onlyModel
After the command is executed , Will find demo The path generates A group called model Folder , There's one in the folder student.gen.go file , This is what we just generated model The file
If you want to specify model Path to file , Need to add -modelPkgName Parameters , The complete command is as follows , After execution ,model Files will be generated in aaa Under the path , We need to pay attention to -modelPkgName The path of needs to be an absolute path , It can't be a relative path .
gentool -dsn "root:[email protected](127.0.0.1:3306)/my_test_db?charset=utf8mb4&parseTime=True&loc=Local" -tables student" -onlyModel -modelPkgName="/Users/luochunhui/go/src/demo/aaa"
2、 Change file name
We are usually used to putting student.gen.go This model In the document '.gen' String removal , That is, rename it to student.go
3、model Add necessary comments to the file
Next we need to use model File generation queryset file , That is what we often see '_gen.go' Final document , Generate queryset Before document , Need to be in model Add... To the file 2 Line notes , Although it is a comment , But these two lines of comments are essential .
student.go It is the present. model File name of the file ,student_gen.go Is to be generated queryset File name of the file
//go:generate goqueryset -in student.go -out student_gen.goThe following line of logs must be placed in model struct First row directly above .
// gen:qs4、 install goqueryset
Execute the following command to goqueryset Tool installation
go get -u github.com/jirfag/go-queryset/cmd/goqueryset
# If the top go get Command to install goqueryset Failure , You can try the following command , If you succeed, you don't have to try
go install github.com/jirfag/go-queryset/cmd/[email protected]
5、 Generate queryset file
After adding comments , Enter into model File path , Execute the following command to generate queryset file .
go generate ./...
After execution, you can see the and model A file is generated under the same level directory student_gen.go file , This file is queryset file .
6、 Last
In the generated queryset You can see github.com/jinzhu/gorm This dependency has not been installed yet , Execute the following command to pull , No error should be reported after pulling .
go get github.com/jinzhu/gorm
go mod tidy边栏推荐
- Data consistency between redis and database
- 你知道Oracle的数据文件大小有上限么?
- Error: eacces: permission denied, access to "/usr/lib/node_modules"
- MySQL45讲——学习极客时间MySQL实战45讲笔记—— 05 | 深入浅出索引(下)
- Word frequency statistics & sorting
- Systemserver process
- P1347 排序(拓扑 + spfa判断环 or 拓扑[内判断环])
- Selenium installing selenium in pycharm
- Winter vacation daily question - lucky numbers in the matrix
- 万物生长大会在杭召开,当贝入选2022中国未来独角兽TOP100榜单
猜你喜欢

Don't spend money, spend an hour to build your own blog website

Solution: Compression Technology (original version and sequel version)

Mysql5.7 installation super easy tutorial

Gee learning notes 2

In 2021, the global revenue of structural bolts was about $796.4 million, and it is expected to reach $1097.6 million in 2028

Development skills of rxjs observable custom operator

Qt-制作一个简单的计算器-实现四则运算-将结果以对话框的形式弹出来

OpenFOAM:lduMatrix&lduAddressing

2022家用投影仪首选!当贝F5强悍音画效果带来极致视听体验

默认插槽,具名插槽,作用域插槽
随机推荐
QT - make a simple calculator - realize four operations
Multi rotor aircraft control using PID and LQR controllers
[Blue Bridge Cup] children's worship circle
Dingtalk 发送消息
全屋Wi-Fi:一个谁也解决不好的痛点?
代码实现MNLM
Error function ERF
[document tree, setting] font becomes smaller
[template] longest common subsequence ([DP or greedy] board)
693. 行程排序(map + 拓扑)
The conference on the growth of all things was held in Hangzhou, and dangbei was selected into the top 100 list of future unicorns in China in 2022
ensp简单入门
selenium,元素操作以及浏览器操作方法
2022 home projector preferred! Dangbei F5 brings the ultimate audio-visual experience with its powerful audio-visual effect
Mysql5.7 installation super easy tutorial
ArrayList and LinkedList
如何设置Qt手工布局
Selenium installing selenium in pycharm
P1042 [noip2003 popularization group] Table Tennis
Astro learning notes