Gordana Tasic

Gordana Tasic

  • 2k
  • 63
  • 3k

Problem with one-to-many relation in MySQL

Jul 12 2021 11:29 AM

I'm developing NestJS app with MySQL. I have two tables (Sport and Referee) with one-to-many relation between them. When I test the create operation, the foreign key in Referee table is null. Also, I can't read referees for a certain sport. Can anyone check what the problem is?Here is the code:

//class Sport
@Entity()
export class Sport
{
@PrimaryGeneratedColumn("uuid")
id: string;

@Column()
name: string;

@OneToMany(type => Referee, ref => ref.sport)
referees: Referee[];
}

//class Referee
@Entity()
export class Referee
{
@PrimaryGeneratedColumn("uuid")
id: string;

@Column()
name: string;

@ManyToOne(type => Sport, sp => sp.referees)
sport: Sport;
}

//code in referee service
async findBySport(sportId: string): Promise<Referee[]>
{
    return await this.refereesRepository.find({where: {id: sportId}});
}

async add(referee: Referee)
{
    await this.refereesRepository.save(referee);
}
}
 
//code in controller   
@Get()
getRefereesBySport(@Param('sportId') sportId: string)
{
    return this.refereesService.findBySport(sportId);
}
}