[英]How to map joined table column to an entity's field in TypeORM
There are two entities as follow:有两个实体如下:
// user.entity.ts
@Entity()
export class User extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
@RelationId((user: User) => user.group)
groupId: number;
@Column()
fullName: string;
@Column()
email: string;
@Column()
passwordHash: string;
@ManyToOne(type => Group, group => group.users)
@JoinColumn()
group: Group;
isOwner: boolean;
}
// group.entity.ts
@Entity()
export class Group extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column({ default: false })
isOwner: boolean;
@OneToMany(type => User, user => user.group)
users: User[];
}
I'd like to map the isOwner
value of Group
to isOwner
of User
我想将
Group
的isOwner
值映射到User
isOwner
I tried:我试过:
async findOneById(id: number): Promise<User> {
return await User.createQueryBuilder('user')
.leftJoinAndMapOne('user.isOwner', 'user.group', 'group')
.select(['user.id', 'user.fullName', 'user.email', 'group.isOwner'])
.getOne();
}
the result was:结果是:
It is possible to achieve that by using @AfterLoad()
or with JS or with raw query.可以通过使用
@AfterLoad()
或使用 JS 或使用原始查询来实现。
Is it possible to implement that using the orm on the query level?是否可以在查询级别使用 orm 来实现?
Something like that could be as a solution:这样的事情可以作为解决方案:
findOneById(id: number): Promise<User> {
return User.createQueryBuilder('user')
.leftJoinAndMapOne('user.isOwner', 'user.group', 'group')
.select(['user.id', 'user.fullName', 'user.email', 'group.isOwner AS user.isOwner']) // or probably 'group.isOwner AS user_isOwner'
.getOne();
}
And you could look at this answer , hope it would be helpful你可以看看这个答案,希望它会有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.