首页 > 解决方案 > 如何使用 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

标签: postgresqltypescriptmany-to-manytypeorm

解决方案


我找到了:

// 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[];

推荐阅读