gpt4 book ai didi

mysql - Typeorm如何获取关系的关系

转载 作者:行者123 更新时间:2023-11-29 15:26:44 30 4
gpt4 key购买 nike

我正在使用 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
}

这是我的实体:

用户实体


@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;

}

最佳答案

我们可以通过在 relations 数组本身中使用 'relation.subrelation' 来加载子关系,如下所示:

关系:['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

关于mysql - Typeorm如何获取关系的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59031198/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com