我正在使用entitymanager.findOne
方法获取对象ChatRoomEntity。 ChatRoomEntity具有变量messages
,该变量为OneToMany-ManyToOne关系。我选择它没有问题,但是如何获得发送邮件的用户。它是MessageEntity上具有OneToMany关系的变量。
因此,基本上我想选择一个房间及其所有消息。但所有消息也应在fromUser
上具有其值。
我选择这样的房间:
this.entityManager.findOne(ChatRoomEntity, {where: {id: roomToJoin.id}, relations: ['activeUsers', 'messages']}).then(roomEntity => {
// some code
}
这是我的实体:
UserEntity
@Entity()
export class UserEntity {
@PrimaryGeneratedColumn()
id: number;
@CreateDateColumn()
registrationDate: Date;
@ManyToMany(type => ChatRoomEntity, room => room.activeUsers, {cascade: true})
@JoinTable()
activeChatRooms: ChatRoomEntity[];
@OneToMany(type => ChatRoomMessageEntity, msg => msg.fromUser)
chatRoomMessages: ChatRoomMessageEntity[];
}
ChatRoomEntity
@Entity()
export class ChatRoomEntity {
@PrimaryGeneratedColumn()
id: number;
@Column('varchar', {nullable: true})
title: string;
@OneToMany(type => ChatRoomMessageEntity, chatrmsg => chatrmsg.chatRoom)
messages: ChatRoomMessageEntity[];
@ManyToMany(type => UserEntity, user => user.activeChatRooms)
activeUsers: UserEntity[];
}
ChatRoomMessageEntity
@Entity()
export class ChatRoomMessageEntity {
@PrimaryGeneratedColumn()
id: number;
@Column('varchar', {nullable: true})
message: string;
@CreateDateColumn()
creationDate: Date;
@ManyToOne(type => UserEntity, user => user.chatRoomMessages)
fromUser: UserEntity;
@ManyToOne(type => ChatRoomEntity, chatRoom => chatRoom.messages)
chatRoom: ChatRoomEntity;
}
答案 0 :(得分:9)
我们可以通过在'relation.subrelation'
数组本身中使用relations
来加载子关系,如下所示:
relations: ['relation1', 'relation2', 'relation2.subrelation1']
因此,对于您的情况,无需使用join即可执行以下操作:
this.entityManager.findOne(ChatRoomEntity, {
where: {id: roomToJoin.id},
relations: ['activeUsers', 'messages', 'messages.fromUser'],
}).then(roomEntity => {
...
在此处指定:https://github.com/typeorm/typeorm/blob/master/docs/find-options.md#basic-options
答案 1 :(得分:4)
await getRepository(Entity)
.createQueryBuilder('user')
.leftJoinAndSelect('user.photo', 'photo')
.leftJoinAndSelect('photo.photometa', 'photometa')
.getMany()
答案 2 :(得分:0)
好的,解决方案很简单。为了得到我需要的东西,我只是使用了这样的联接:
this.entityManager.findOne(ChatRoomEntity, {
where: {id: roomToJoin.id},
relations: ['activeUsers', 'messages'],
join: {
alias: 'cr', innerJoinAndSelect: {
messages: 'cr.messages',
users: 'messages.fromUser'
}
}
}).then(roomEntity => {
...