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

如何解决使用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;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-