TypeORM级联选项:级联,onDelete,onUpdate [英] TypeORM cascade option: cascade, onDelete, onUpdate

查看:87
本文介绍了TypeORM级联选项:级联,onDelete,onUpdate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TypeORM中的级联选项是否重叠或它们的用途完全不同?文档中对它们的描述非常稀缺,部分缺失,或者我找不到.

Do cascade options in TypeORM overlap or do they have a completely different purpose? Their description in the documentation is very scarce and partly missing, or I couldn't find it.

IOW,请执行以下选项

IOW, do the following options

{级联:"update"} = {onUpdate:'CASCADE'}

{级联:删除"} = {onDelete:'CASCADE'}

有同样的效果吗?

还是 cascade 选项仅用于TypeORM,而 onUpdate onDelete 仅用于DB模式(通过迁移创建)?

Or the cascade option is only for the TypeORM use while onUpdate and onDelete are only for the DB schema (created by migration)?

推荐答案

这是我研究它的结论:

cascade 选项不会影响数据库列约束,我相信TypeORM仅将其用于评估如何将实体关系保存到数据库中.我们可以这样定义实体:

The cascade option does not affect the database column constraints, and I believe is used by TypeORM only in evaluating how to save entity relations to the database. We can define entities like this:

@Entity()
class Book extends BaseEntity {
    @ManyToOne(() => Author, (author) => author.books, {
        onDelete: 'CASCADE',
    })
    public author?: Author
}

@Entity()
class Author extends BaseEntity {
    @OneToMany(() => Book, (book) => book.author, {
        cascade: true,
    })
    public books: Book[];
}

onDelete authorId 外键设置为 Book 上的CASCADE onDelete.这意味着当作者被删除时,这本书也将被删除.

onDelete sets the authorId foreign key to CASCADE onDelete on Book. This means that when the author is deleted, the book is also deleted.

Author 上设置 cascade:true 会告诉TypeORM:如果在作者身上添加了新书并且保存了作者,则还应将新书保存到数据库.像这样:

Setting cascade: true on Author tells TypeORM that if a new book is appended on an author and the author is saved, the new book should also be saved to the database. Like this:

const author = await Author.findOne({ id: '123' });
author.books.push(new Book(...));
await author.save();

如果未在 Book 上设置级联,则新书不会保存到数据库中.

If cascade is not set on Book, the new book will not be saved to the database.

这篇关于TypeORM级联选项:级联,onDelete,onUpdate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆