我有一个用户实体,它有一个userRoles数组作为数据成员。用户存储在数据库中名为users的表中,user_roles存储在名为user_role_mapping的表中。我想与typeorm建立一对多关系,这样当我在数据库中保存用户时,它也会在相应的表中保存相应的userRoles。我还没能让它发挥作用。
这是我的用户实体
@Entity("users",{schema:"Cellphones" } )
@Index("net_id",["netId",],{unique:true})
export class User {
@PrimaryGeneratedColumn({
type:"int",
name:"id"
})
id: number;
@Column("varchar",{
nullable:false,
unique: true,
length:20,
name:"net_id"
})
netId: string;
@Column("varchar",{
nullable:true,
length:20,
name:"employee_id"
})
employeeId: string | null;
@Column("varchar",{
nullable:false,
length:50,
name:"first_name"
})
firstName: string;
@Column("varchar",{
nullable:false,
length:50,
name:"last_name"
})
lastName: string;
@Column("varchar",{
nullable:true,
length:50,
name:"title"
})
title: string | null;
@Column("tinyint",{
nullable:false,
width:1,
name:"active"
})
active: boolean;
@Column("varchar",{
nullable:true,
length:100,
name:"email"
})
email: string | null;
@Column("varchar",{
nullable:true,
length:20,
name:"phone"
})
phone: string | null;
@Column("date",{
nullable:true,
name:"term_date"
})
termDate: Date | null;
@Column("varchar",{
nullable:true,
length:10,
name:"term_department"
})
termDepartment:string | null;
@Column("date",{
nullable:true,
name:"retire_date"
})
retireDate: Date | null;
@Column("date",{
nullable:false,
name:"last_login"
})
lastLogin: Date;
@Column("varchar",{
nullable:false,
length:50,
name:"employee_status"
})
employeeStatus:string;
@Column("varchar",{
nullable:false,
length:50,
name:"department"
})
department:string;
@Column("varchar",{
nullable:true,
length:10,
name:"pay_group"
})
payGroup:string | null;
@Column("datetime",{
nullable:true,
name:"updated"
})
updated:Date | null;
@Column("int",{
nullable:true,
name:"updated_by"
})
updatedBy:number | null;
@Column("date",{
nullable:true,
name:"inactivated"
})
inactivated:Date | null;
@Column("int",{
nullable:true,
name:"inactivated_by"
})
inactivatedBy:number | null;
@OneToMany(type => UserRoleMapping, userRoleMapping => userRoleMapping.userId)
userRoles: UserRoleMapping[];
}
这是我的UserRoleMapping实体:
@ManyToOne(type => User, user => user.userRoles)
@Entity("user_role_mapping",{schema:"Cellphones" } )
export class UserRoleMapping {
constructor(id: number, userId: number, roleId: number) {}
@PrimaryGeneratedColumn({
type:"int",
name:"id"
})
id: number;
@Column({
type:"int",
name:"user_id"
})
userId: number;
@Column({
type:"int",
name:"role_id"
})
roleId: number;
}
下面是users表的样子:
小时
下面是user_role_mapping表的样子:
小时
请注意,任何名称以old_开头的列仅用于数据迁移目的,与此项目无关。
2条答案
按热度按时间o7jaxewo1#
实体
UserRoleMapping
的定义中存在一些错误:@Entity
的schema
选项将被忽略。如果您喜欢不同于实体属性名称的列和表的自定义命名策略,可以在TypeORM配置中全局定义。对于较小的调整,您可以从DefaultNamingStrategy导出。
fnvucqvd2#
这是使关系工作的代码。
在用户中:
在UserRoleMapping中:
关键是将关系修饰符移动到用户字段并定义@JoinColumn。