TypeORM-获取所提供id的对象,这是一个关系



我想从提供id的表中获取对象,该表与处于另一关系中的表有关。它看起来像这样:

手与manyToOne有动作(手只能有一个动作(,行动与多种情况有关一对一(行动只能有一种情况(

我正在尝试对我提供情境ID的手进行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, { onDelete: 'CASCADE', 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 }
}
}
});

相关内容

最新更新