Typeorm 关系 - 按 id 保存

Mau*_*cco 12 typeorm nestjs

我对这些关系有点困惑,因为我习惯通过 id 保存关系,而我发现的文档和示例建议获取整个对象并使用它(这不是很奇怪吗???)

我在 github 上发现了这个问题(https://github.com/typeorm/typeorm/issues/447),他们建议使用仅具有 id 属性的对象,但它是从 2017 年开始的。这是一个好方法吗?做吗?这仍然是唯一的方法吗?(我觉得这很蹩脚)

async create( @Body() product: Product) {
    product.category = <any>{ id: product.category };
    return { payload: await this.repository.persist(product) };
}
Run Code Online (Sandbox Code Playgroud)

另一位建议将该列命名为categoryId,它将按预期工作(使用 id 而不是 object),但为什么呢?这个名字有什么关系??

@Entity()
class Product {

     @Column({ type: "int", nullable: true })
     categoryId: number;

     @ManyToOne(type => Category)
     @JoinColumn({ name: "categoryId" })
     category: Category;

}
Run Code Online (Sandbox Code Playgroud)

我很困惑,请帮忙^_^

Uro*_*lić 10

这不奇怪吗???

取决于你怎么想,但是,是的,我也喜欢能够只设置 id,而不是获取整个相关实体。

这是一个好方法吗?这仍然是唯一的方法吗?

我也在弄清楚 typeorm 的过程中。我发现你可以这样做:

product.category = <any>3;
// or
product['category' as any] = 3;
repository.save(product) // I don't know how you have the persist() method.
Run Code Online (Sandbox Code Playgroud)

并且,在您的情况下,product.categoryId列将设置为3。如果categoryId是外键并且您设置了一个不存在的id,您将得到一个外键错误,就像您应该的那样。

但这样 ts 仍然会认为它product.category是 type 的Category。您还可以将该category属性指定为Category | number. 但是这样你就必须到处进行类型检查,这很烦人。我对此进行了一些测试,但我不确定这是否会导致一些毫无戒心的错误。

这个名字有什么关系??

那么您提供的选项是定义 2 个属性:category哪个是关系,categoryId哪个是列。该属性的categoryId命名应类似于表中的列,但您也可以name: 'actual_name'@Column装饰器中传递。我不知道如果您同时设置两个属性columnIdcolumn具有不同 id 的属性会发生什么。


All*_*uan 5

根据这个 GitHub thread,似乎你也可以做这样的事情:

product.category = { id: 1 }
product.save()

// Or
product.category = new Category().id = 1
product.save()
Run Code Online (Sandbox Code Playgroud)