postgresql - 如何使用 TypeORM 设置与自定义 id 名称的多对多关系
问题描述
我有一个用户、角色和 user_role 表。
当我建立@ManyToMany 关系时,当我尝试加入表时出现错误,因为查询使用“roleId”,但我将其命名为“role_id”,我无法弄清楚如何设置列名。
// User.ts
@ManyToMany(type => Role, role => role.users)
@JoinTable({name: 'user_role'})
roles?: Role[];
// Role.ts
@ManyToMany(type => User, user => user.roles)
@JoinTable({name: 'user_role'})
users: User[];
要查询的 UserService:
public static getAllByRole(role: RoleEnum): Promise<User[]> {
return this.userRepository()
.createQueryBuilder('user')
.leftJoinAndSelect(
'roles',
'role',
'role.user_id = user.id'
).where('role.role_id = :id', {id: role})
.getMany();
}
我希望获得具有特定角色的所有用户,例如“管理员”。
但它会引发错误:
console.log node_modules/typeorm/platform/PlatformTools.js:193
query failed: INSERT INTO "user_role"("roleId", "userId") VALUES ($1, DEFAULT), ($2, DEFAULT) -- PARAMETERS: ["ROLE_ADMIN","ROLE_USER"]
console.log node_modules/typeorm/platform/PlatformTools.js:193
error: { error: column "roleId" of relation "user_role" does not exist
解决方案
我找到了:
// User.ts
@Field(type => [Role])
@ManyToMany(type => Role, role => role.users)
@JoinTable({
name: 'user_role', joinColumn: {
name: 'user_id',
referencedColumnName: 'id'
},
inverseJoinColumn: {
name: 'role_id',
referencedColumnName: 'id'
}
})
roles?: Role[];
// Role.ts
@ManyToMany(type => User, user => user.roles)
@JoinTable({
name: 'user_role',
joinColumn: {
name: 'role_id',
referencedColumnName: 'id'
},
inverseJoinColumn: {
name: 'user_id',
referencedColumnName: 'id'
}
})
users: User[];
推荐阅读
- django - 模板中的Django for循环不会循环遍历元素,就像一个大字符串
- c++ - “变量周围的堆栈已损坏”。如何确定数组的大小?
- performance - 预测提取的 Coq 代码到 Haskell 的运行时间
- php - How to log details in php xml file for Twilio sms response
- linux - fork 的子进程返回值在哪里?
- javascript - 无法读取函数中未定义的属性“0”(p5.js)
- apache-kafka - Spring Cloud Stream Kafka 应用程序未使用正确的 Avro 模式生成消息
- swift - 排序协议数组,寻找父协议
- javascript - Syntax to set the color of a circle using data
- javascript - Why does fetch keep cutting out when downloading a file while manual download in the browser doesn't?