安裝工具
go install github.com/go-home-admin/toolset
建立資料庫結構
CREATE TABLE `users` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`email_verified_at` timestamp NULL DEFAULT NULL,
`password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `users_email_unique` (`email`) USING HASH
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
建立配置檔案
# 所有資料庫連線
connections:
mysql:
driver: mysql
host: env("DB_HOST", "127.0.0.1")
port: env("DB_PORT", "3306")
database: env("DB_DATABASE", "home-mysql")
username: env("DB_USERNAME", "root")
password: env("DB_PASSWORD", "123456")
# 生成orm輔助關係
helper:
admin_menu:
- with: belongs_to
table: admin_role_menu
alias: AdminRoleMenu
gorm: "foreignKey:id;references:menu_id"
執行命令生成程式碼
user@macOs path $ toolset make:orm -config=./config/database.yaml -out=your_path
使用生成的程式碼
func TestNewOrmUsers(t *testing.T) {
// 讀取一條資料
user, has := NewOrmUsers().WhereId(1).First()
fmt.Println(user, has)
// 讀取列表資料 select * from users where id > 1 and create_ed >= now() limit 16
users := NewOrmUsers().WhereIdGt(1).WhereCreatedAtGte(database.Now()).Limit(15).Get()
fmt.Println(users)
// 結果的輔助函式
ids := users.GetIdList()
fmt.Println( NewOrmUsers().WhereIdIn(ids).Get() )
fmt.Println(users.GetIdMap())
}
生成的demo 可以檢視
github.com/go-home-admin/go-admin/...
本作品採用《CC 協議》,轉載必須註明作者和本文連結