TypeORM cyclic dependency with OneToOne and ManyToOne

Viewed 1091

I've got these two entities related to each other:

@Entity()
export class Message {

    // ... other columns ...

    @OneToMany(() => Action, action => action.message, { eager: true, cascade: true })
    public actions: Action[];
}
@Entity()
export class Action {

    // ... other columns ...

    @ManyToOne(() => Message, message => message.actions, { nullable: false })
    public message?: Message;
}

But I want to record on the message entity when the user takes an action. I try adding an extra relation to the message like this:

@Entity()
export class Message {

    // ... other columns ...

    @OneToMany(() => Action, action => action.message, { eager: true, cascade: true })
    public actions: Action[];

    @OneToOne(() => Action, { nullable: true })
    @JoinColumn()
    public action_taken: Action;
}

But when trying to save a new message with the actions relation populated (trying to save them all at once with cascade: true), then I get the following error:

TypeORMError: Cyclic dependency: "Action"
    at new TypeORMError (/app/node_modules/typeorm/error/TypeORMError.js:9:28)
    at visit (/app/node_modules/typeorm/persistence/SubjectTopoligicalSorter.js:144:23)
    at visit (/app/node_modules/typeorm/persistence/SubjectTopoligicalSorter.js:160:21)
    at visit (/app/node_modules/typeorm/persistence/SubjectTopoligicalSorter.js:160:21)
    at SubjectTopoligicalSorter.toposort (/app/node_modules/typeorm/persistence/SubjectTopoligicalSorter.js:139:17)
    at SubjectTopoligicalSorter.sort (/app/node_modules/typeorm/persistence/SubjectTopoligicalSorter.js:53:45)
    at SubjectExecutor.<anonymous> (/app/node_modules/typeorm/persistence/SubjectExecutor.js:99:124)
    at step (/app/node_modules/tslib/tslib.js:143:27)
    at Object.next (/app/node_modules/tslib/tslib.js:124:57)
    at /app/node_modules/tslib/tslib.js:117:75

Setting cascade: false doesn't throw the error, but then it also doesn't save the related records.

What am I missing? Is there a way I can still have cascade: true and have a double relation to an entity? Or will I have to manually save the related records?

1 Answers

Had this problem, in a @ManyToOne @OneToMany relationship, It can be solved by removing the side of the relationship that is without cascade. The error goes away, and the cascade works.

Related