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
{
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);
}
}
Ajay BansodePosted Aug 22, 2025, 11:48 AM
I see the issue — there are two separate problems in your code that explain why:
The foreign key is
NULLwhen inserting a refereeYour query for referees by sport doesn’t work
1. Why the foreign key is
NULLWhen you save a
Referee, you are not setting thesportfield before callingsave.In TypeORM, the
@ManyToOneside owns the foreign key, so you must explicitly assign aSport(or at least itsid) when saving.If you just call
save(referee)without assigning.sport, thesportIdcolumn staysNULL.2. Why you can’t read referees for a sport
In your
findBySportmethod, you are filtering on the referee’s ownid, not on its relation’sid.Your current code:
… will only match referees whose own
idequals the sport’s id — which never happens.3. Controller fix
If your route looks like
/sports/:sportId/referees, you need to passsportIdcorrectly:Summary of fixes
In
add(), assign thesportwhen saving aReferee.In
findBySport(), filter by{ sport: { id: sportId } }, not{ id: sportId }.Ensure your controller route matches the parameter (
:sportId).