mysql之在 Gorm 中使用模型连接两个表的最佳方法是什么

pander-it 阅读:213 2025-06-02 22:19:02 评论:0

我坚持使用 GORM 加入两个表。经过所有研究,我发现预加载可以解决问题。但是,我不清楚如何使用它。我尝试了很多方法,但都没有奏效。我有两张 table 。用户和角色。每个用户将与一个角色相关联。
这是用户表的架构

CREATE TABLE `users` ( 
  `id` int NOT NULL AUTO_INCREMENT, 
  `first_name` varchar(45) NOT NULL, 
  `last_name` varchar(45) NOT NULL, 
  `email` varchar(45) NOT NULL, 
  `password` varchar(45) NOT NULL, 
  `app_id` int NOT NULL, 
  `created_at` datetime DEFAULT NULL, 
  `deleted_at` datetime DEFAULT NULL, 
  `updated_at` datetime DEFAULT NULL, 
  `verifications` json DEFAULT NULL COMMENT 'A json Object in a specific format.\n{\n Verification_Code : {\n       isCompleted: Bool,\n       message: "Some custom message",\n      extraInfo: {}\n  }\n}', 
  `role_id` int NOT NULL, 
  `status` int NOT NULL COMMENT '0 = Good Status and active account\n> 0 = Bad Status and deactive account', 
  `company_id` int DEFAULT NULL, 
  PRIMARY KEY (`id`), 
  UNIQUE KEY `unique_index` (`email`,`app_id`), 
  KEY `role_key_colmn_idx` (`role_id`), 
  KEY `app_key_column_idx` (`app_id`), 
  KEY `company_id` (`company_id`), 
  CONSTRAINT `app_key_column` FOREIGN KEY (`app_id`) REFERENCES `applications` (`id`), 
  CONSTRAINT `role_key_colmn` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`), 
  CONSTRAINT `users_ibfk_1` FOREIGN KEY (`company_id`) REFERENCES `companies` (`id`) 
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci 
角色表的架构:
CREATE TABLE `roles` ( 
  `id` int NOT NULL AUTO_INCREMENT, 
  `name` varchar(45) NOT NULL, 
  `description` varchar(45) DEFAULT NULL, 
  `app_id` int NOT NULL, 
  `code` varchar(45) NOT NULL, 
  `created_at` datetime DEFAULT NULL, 
  `updated_at` datetime DEFAULT NULL, 
  `deleted_at` datetime DEFAULT NULL, 
  PRIMARY KEY (`id`), 
  UNIQUE KEY `code_UNIQUE` (`code`), 
  KEY `App_Id_conn_idx` (`app_id`), 
  CONSTRAINT `App_Id_conn` FOREIGN KEY (`app_id`) REFERENCES `applications` (`id`) 
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci 
用户实体模型:
type User struct { 
    gorm.Model 
    FirstName     string `gorm:"column:first_name;not_null"` 
    LastName      string `gorm:"column:last_name;not_null"` 
    Email         string `gorm:"column:email;not_null"` 
    Password      string `gorm:"column:password;not_null"` 
    AppId         uint   `gorm:"column:app_id;not_null"` 
    Verifications string `gorm:"column:verifications;not_null"` 
    Status        int    `gorm:"column:status;not_null"` 
    Role          Role 
    Company       Company 
} 
 
func (User) TableName() string { return "users" } 
角色实体模型:
type Role struct { 
    gorm.Model 
    Name string `gorm:"column:name;not_null"` 
    Description string `gorm:"column:description"` 
    AppId uint `gorm:"column:app_id;not_null"` 
    Code string `gorm:"column:code;not_null;"` 
} 
 
func (Role) TableName() string { return "roles" } 
这是我正在使用的查询:
err := r.db.Where(&Entity.User{AppId: appId, Email: username, Password: password}).Take(&u).Error; 
这是填充用户信息而不是角色信息。任何帮助将不胜感激。在 Spring Boot 中,它曾经通过设置一些 @annotations 来自动填充,但在这里我不确定它是如何工作的。

请您参考如下方法:

首先,您需要在模型本身中添加外键字段并在字段标签中指定列名,除非您使用 default。外键列的 GORM 命名约定。然后需要在引用模型gorm:"foreignkey:RoleId"上添加外键的gorm字段标签

type User struct { 
    gorm.Model 
    FirstName     string `gorm:"column:first_name;not_null"` 
    LastName      string `gorm:"column:last_name;not_null"` 
    Email         string `gorm:"column:email;not_null"` 
    Password      string `gorm:"column:password;not_null"` 
    AppId         uint   `gorm:"column:app_id;not_null"` 
    Verifications string `gorm:"column:verifications;not_null"` 
    Status        int    `gorm:"column:status;not_null"` 
    Role          Role   `gorm:"foreignkey:RoleId"` 
    RoleId        int 
    Company       Company 
} 
然后急切加载您可以使用的角色 Preload err := r.db.Preload('Role').Where(&Entity.User{AppId: appId, Email: username, Password: password}).Take(&u).Error;


标签:mysql
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号