【问题标题】:Typeorm relationships - save by idTypeorm 关系 - 按 id 保存
【发布时间】:2020-06-20 06:01:44
【问题描述】:

我对关系有点困惑,因为我习惯于通过 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) };
}

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

@Entity()
class Product {

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

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

}

我很困惑,求助^_^

【问题讨论】:

    标签: nestjs typeorm


    【解决方案1】:

    这不奇怪吗???

    取决于你的想法,但是,是的,我也喜欢能够只设置 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.
    

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

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

    这个名字和那个有什么关系??

    您提供的选项是定义 2 个属性:category 是关系,categoryId 是列。属性categoryId 应该像表中的列一样命名,但您也可以在@Column 装饰器中传递name: 'actual_name'。我不知道如果您将columnIdcolumn 属性都设置为不同的ID 会发生什么。

    【讨论】:

    • “你可以只做product.category = 3”是什么意思?我收到了一个类型错误,你的意思是即使它给出了一个类型错误它也能工作?
    • 你是对的。我在节点 REPL 中测试我的代码,它工作,因为它只是 js。我将编辑我的答案。
    【解决方案2】:

    根据this GitHub thread,看来你也可以这样做:

    product.category = { id: 1 }
    product.save()
    
    // Or
    product.category = new Category().id = 1
    product.save()
    

    【讨论】:

      猜你喜欢
      • 2020-04-06
      • 2019-04-24
      • 2021-08-09
      • 2021-01-04
      • 2019-07-20
      • 2021-10-18
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      相关资源
      最近更新 更多