I got two entities with relation like this
@Entity()
export class Parent extends BaseEntity {
@IsEmpty({groups: [CrudValidationGroups.CREATE]})
@ApiProperty()
@PrimaryGeneratedColumn()
public id: number;
@ApiProperty()
@IsString({always: true})
@Column({nullable: false})
public name: string;
@ApiProperty({type: () => [Child]})
@OneToMany(() => Child, child => child.parent)
public children: Child[];
}
@Entity()
export class Child extends BaseEntity {
@IsEmpty({groups: [CrudValidationGroups.CREATE]})
@ApiProperty()
@PrimaryGeneratedColumn()
public id: number;
@ApiProperty()
@Column()
public name: string;
@ApiProperty({type: () => Parent})
@ManyToOne(() => Parent, parent => parent.children, {onDelete: "SET NULL"})
public parent: Parent;
@Column()
public parentId: number;
with /parent controller
@Crud({
model: {type: Parent},
routes: {exclude: ["replaceOneBase", "createManyBase"]},
query: {
alwaysPaginate: true,
join: {
children: {
eager: true,
},
},
},
})
export class ParentsController {}
When I try to create both Parent and Child in one POST call to ParentsController, only Parent is created.
POST /parents
{
"name": "Peter sr.",
"children": [{
"name": "Peter jr."
}]
}
{
"id": 1,
"name": "Peter sr.",
"children": []
}
But when Child is created beforehand and id is provided, it assigns Child to the Parent.
POST /parents
{
"name": "Peter sr.",
"children": [{
"id": 1
}]
}
{
"id": 1,
"name": "Peter sr.",
"children": [{
"id": 1,
"name": "Peter jr.",
"parentId": 1,
}]
}
Is there any trick that allows me to use the first scenario with result of the second? I can @Override createOne and deal with children array seperately. But it would be nice if this can be handled by CRUD.
I hate when I find solution right after I asked online. It's more related to TypeORM. { cascade: true } on Parent.children relation does the trick.
Most helpful comment
I hate when I find solution right after I asked online. It's more related to TypeORM.
{ cascade: true }onParent.childrenrelation does the trick.