使用Gorm中的模型来连接两个表的最佳方法是什么?

问题描述

我被困在使用GORM连接两个表的过程中。经过所有研究,我发现预紧力可以解决问题。但是,我不清楚如何使用它。我尝试了很多方法,但是都没有用。我有两个桌子。用户和角色。每个用户将与一个角色相关联。

这是用户表的架构

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,`code` varchar(45) NOT NULL,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;

这是在填充用户信息,而不是角色信息。任何帮助将不胜感激。在春季启动中,它曾经通过设置一些@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;