[英]TypeORM cyclic dependency with OneToOne and ManyToOne
我有這兩個相互關聯的實體:
@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;
}
但是我想在用戶采取行動時記錄在消息實體上。 我嘗試像這樣向消息添加額外的關系:
@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;
}
但是,當嘗試保存填充了actions
關系的新消息時(嘗試使用cascade: true
一次保存它們),然后出現以下錯誤:
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
設置cascade: false
不會拋出錯誤,但也不會保存相關記錄。
我錯過了什么? 有沒有辦法我仍然可以擁有cascade: true
並且與實體有雙重關系? 還是我必須手動保存相關記錄?
有這個問題,在 nest CLI 上工作正常,但在使用無服務器和 webpack 時出現問題。 Typeorm 不適用於 webpack。 我使用了 repository.save (entity) 並且總是因循環依賴而失敗。
切換到后
repository.createQueryBuilder()
.insert()
.values(data)
.execute();
此錯誤已被清除。 我真的建議嘗試更改存儲庫方法,因為 save() 方法等待完整的實體集,而 createQueryBuilder() 獲取實體值並將它們轉換為字符串值,進行正常查詢。
有這個問題,在@ManyToOne
@OneToMany
關系中,可以通過刪除沒有cascade
的關系的一側來解決。 錯誤消失,級聯工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.