【发布时间】:2020-08-11 23:00:21
【问题描述】:
在我的小型 Nest.js 项目中,我有两个实体:Player、League,它们使用带有一些附加属性的 PlayerLeagueStats 表与 ManyToMany 关联(OneToMany - (ManyToOne, ManyToOne) - OneToMany 模式)。当我尝试使用 QueryBuilder 将玩家分配到联赛时,将 playerLeagueStats 对象添加到 Player 的查询执行没有问题,但是应该将相同的 playerLeagueStats 添加到 League 的相应查询会引发错误“类构造函数 League 不能在没有的情况下调用'新的'”。我的实体:
@Entity()
export class League {
@OneToMany(type => PlayerLeagueStats, playerLeagueStats => playerLeagueStats.league)
playerLeagueStats: PlayerLeagueStats[];
//other properties..
@Entity()
export class Player {
@OneToMany(type => PlayerLeagueStats, playerLeagueStats => playerLeagueStats.player)
playerLeagueStats: PlayerLeagueStats[];
//other properties ....
@Entity()
export class PlayerLeagueStats {
@PrimaryGeneratedColumn()
Id!: number;
@ManyToOne(type => Player, player => player.playerLeagueStats)
player: Player;
@ManyToOne(type => League, league => league.playerLeagueStats)
league: League;
//other additional properties ....
带有查询的服务方法:
async assignPlayerToLeague(leagueId: number, playerId: number): Promise<League>{
const foundPlayer = await this.playerRepository.findOne(playerId)
const leagueToAssign = await this.LeagueRepository.findOne(leagueId);
const playerLeagueStats= new PlayerLeagueStats();
await this.playerLeagueStatsRepository.save(playerLeagueStats)
await this.playerRepository
.createQueryBuilder()
.relation(Player, "playerLeagueStats")
.of(foundPlayer)
.add(playerLeagueStats);
await this.LeagueRepository
.createQueryBuilder()
.relation(League, "playerLeagueStats")
.of(leagueToAssign)
.add(playerLeagueStats);
return leagueToAssign;
}
我使用 ormconfig 文件加载我的实体,但我也尝试根据 Nest js 文档在 AppModule forRoot() 方法中执行此操作,但仍然遇到相同的错误。
ormconfig.json
{
"type": "mysql",
"host": "localhost",
"port": 3306,
"username": "my_username",
"password": "any_password",
"database": "tennis_league",
"entities": ["dist/**/*.entity{.ts,.js}"],
"synchronize": true
}
和 AppModule:
@Module({
imports: [TypeOrmModule.forRoot(),
LeagueModule,
PlayerModule,
PlayerLeagueStatsModule
],
controllers: [AppController],
providers: [
{
provide: APP_PIPE,
useClass: ValidationPipe,
},
AppService
],
})
export class AppModule {}
错误的原因可能是什么? 一般来说,我是 NodeJS 和 webdev 的新手。如有任何帮助,我将不胜感激。
【问题讨论】:
标签: node.js typescript nestjs typeorm