-
Let's say I have these two entities @Entity()
export class User {
constructor(id: string, name: string) {
this.id = id;
this.name = name;
}
@PrimaryKey({ type: "uuid" })
id!: string;
@Property()
name!: string;
@OneToMany(
() => Post,
(post) => post.userId,
)
posts = new Collection<Post>(this);
} @Entity()
export class Post {
constructor(id: string, name: string, userId: string) {
this.id = id;
this.name = name;
this.userId = userId;
}
@PrimaryKey({ type: "uuid" })
id!: string;
@Property()
name!: string;
@ManyToOne(() => User, { mapToPk: true })
userId!: string;
} When I try to create a new Post (in nest) like this: postRepository.create({ id, name, userId }) It complains that User.name wasn't provided. Seems like I need to reference the full entity of User to create a Post. And I saw this pattern in documentation multiple times as well. Is there a way to model the relationship so I can only provide the id instead of the full User instance? It should still not work if the id points to a User that does not exist |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You mean some runtime validation? Can you share the full error with a stack trace? I checked the tests and found a very similar test that works just fine. Maybe provide a complete reproduction so its clear what you are doing. I would generally discourage using |
Beta Was this translation helpful? Give feedback.
You mean some runtime validation? Can you share the full error with a stack trace? I checked the tests and found a very similar test that works just fine. Maybe provide a complete reproduction so its clear what you are doing.
I would generally discourage using
mapToPk
, as you will lose a lot of features the ORM provides. Note that you can create an entity instance from its PK without loading it withem.getReference()
(and this works natively inem.create
andem.assign
, just pass a FK value in place of a relation and the EM will createem.getReference
automatically for you), so if that was the reason why you tried to use it, it's not really a r…