My entities:
@Entity('games')
class Game {
@PrimaryColumn('uuid', { generated: true })
id: string;
}
@Entity('runs')
class Run {
@PrimaryColumn('uuid', { generated: true })
id: string
@RelationId((run: Run) => run.game)
gameId: string;
@ManyToOne(type => Game)
@JoinColumn({ name: 'game_id' })
game: Game;
}
How can I create and persist a new run, without supplying the full game object (I just have the ID)?
Right now I have to do something like this:
const run = new Run();
run.game = game;
repos.Runs.persist(run);
but I would prefer being able to do something like
const run = new Run();
run.gameId = gameId;
repos.Runs.persist(run);
Thanks.
You can write
const run = new Run();
run.game = { id: gameId };
repos.Runs.persist(run);
If Game has additional properties, TypeScript complains because { id: gameId }
is not the correct shape. Would you recommend doing something like run.game = { id: gameId } as Game
or is there a different preference for this case?
relation id is just to get
your relation id, it won't work if you want to save through it. You have two options, first is what @NoNameProvided suggested (to prevent casting simply do: run.game = new Game(gameId)
, second is to define column together with relation:
@Entity('runs')
class Run {
@PrimaryColumn('uuid', { generated: true })
id: string
@Column({ type: "int", nullable: true }) // both options must be set
gameId: number;
@ManyToOne(type => Game)
@JoinColumn({ name: 'gameId' })
game: Game;
}
Most helpful comment
relation id is just to
get
your relation id, it won't work if you want to save through it. You have two options, first is what @NoNameProvided suggested (to prevent casting simply do:run.game = new Game(gameId)
, second is to define column together with relation: