如何解决TypeORM-获取具有提供的ID的对象,这是一种关系
我想从提供id的表中获取对象,该id与另一个关系的table有关。看起来像这样:
手与具有动作的多对一关系(手只能有一个动作), 动作与“情境”相关联(动作只能有一个情境)
我正在尝试对要提供情境编号的手进行GET请求。
简化的实体:
@Entity()
export class Hand {
@PrimaryGeneratedColumn()
hand_id: number;
@Column()
hand: string;
@ManyToOne(type => Action,action => action.simplifiedhands,{ eager: true,onDelete: 'CASCADE',onUpdate: 'CASCADE' })
action: Action;
}
@Entity()
export class Action {
@PrimaryColumn()
action_id: number;
@ManyToOne(type => Situation,situation => situation.actions,{ onDelete: 'CASCADE',onUpdate: 'CASCADE' })
@JoinColumn({name: 'situation'})
situation: Situation;
@OneToMany(type => Hand,hand => hand.action)
hands: Hand[];
@OneToMany(type => Hand,hand => hand.action)
hands: Hand[];
}
@Entity()
export class Situation {
@PrimaryColumn()
situation_id: number;
@ManyToOne(type => Strategy,strategy => strategy.situations,onUpdate: 'CASCADE' })
strategy: Strategy;
@OneToMany(type => Action,action => action.situation)
actions: Action[];
}
到目前为止,什么方法对我不起作用(只是示例变体):
return await this.handsRepository.find({
relations: ["action","action.situation"],where: {
"situation": id
}
});
和
return await this.handsRepository.find({
join: {
alias: "hands",leftJoinAndSelect: {
"action": "hand.action","situation": "action.situation"
}
},where: {
"situation": id
}
});
通常都是“工作”,但会提供所有记录,就像没有条件一样。
解决方法
在您的情况下,where
中分配给Hand
的对象中的键应该是存储库实体的成员,因为situation
是操作的成员,因此无效。我很惊讶您没有提到任何错误。
您可以执行以下操作之一(例如postgres)
使用查询生成器:
return await this.handsRepository.createQueryBuilder(Hand,'hand')
.leftJoin('hand.action','action')
.leftJoin('action.situation','situation')
.where('situation.id = :id',{ id })
.getMany();
或者,您可以尝试以下操作(不保证成功):
return await this.handsRepository.find({
relations: ["action","action.situation"],where: {
action: {
situation: { id }
}
}
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。