1. CMD进入项目根目录,安装Gen Tool
go install gorm.io/gen/tools/gentool@latest
2. 输入 gentool -h 是否出现帮助手册,有的话就是安装成功
3. 输入命令生成对应数据库所有表结构体文件,我这里使用的是postgres数据库,如果是要切换其他数据库就改下值,例如mysql,我没尝试过,应该是这样,不写–db参数就是默认mysql
gentool --db=postgres --dsn="host=host user=user password=password dbname=database port=port sslmode=disable" --outPath="项目根目录\\gen_models_fun"
执行完之后模型文件默认存放到项目根目录model文件夹里,gen_models_fun这个文件则是模型的ORM方法集成,类似于pythoh django的ORM方法,不用Gen的话可以删除此文件夹
![在这里插入图片描述](https://img-blog.csdnimg.cn/9e40a13e658e4e1b8c86d5fb5b3a312d.png
如果只想生成指定表,在命名后面加入参数 --tables=“tableName,…”
gentool --db=postgres --dsn="host=host user=user password=password dbname=database port=port sslmode=disable" --outPath="项目根目录\\gen_models_fun" --tables="users,tasks"