Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typeorm relationships - save by id

Tags:

I've been kinda confused by the relationships as I'm used to save relationship by id, while docs and examples I found suggest to get the entire object and use that instead (Isn't this strange???)

I found this on github addressing this issue ( https://github.com/typeorm/typeorm/issues/447 ) , where they suggest to use an object with just the id property, but it's from 2017. Is that a good way to do it ? And is it still the only way to do it ? (I find it pretty lame tbh)

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

Another one suggested to name the column as categoryId and it would work as expected (with id instead of object) but WHY? What does the name have to do with that ??

@Entity()
class Product {

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

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

}

I'm just confused, help ^_^

like image 923
Mauro Insacco Avatar asked Mar 07 '20 20:03

Mauro Insacco


2 Answers

Isn't this strange???

Depends how you think about it, but yeah, I also like being able to just set the id, and not fetch the entire related entity.

Is that a good way to do it ? And is it still the only way to do it ?

I am also in the process of figuring out typeorm. What I found out is that you can do:

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

and, in your case, the product.categoryId column will be set to 3. If categoryId is a foreign key and you set a non-existing id, you will get a foreign key error, like you should.

But this way ts will still think that product.category is of type Category. You can also specify the category property as a Category | number. But then you would have to do type checks everywhere which is annoying. I've tested this a bit, but I'm not sure if this will cause some unsuspecting bugs.

What does the name have to do with that ??

Well the option you provided is to define 2 properties: category which is a relation, and categoryId which is the column. The property categoryId should be named like the column in the table, but you can also pass the name: 'actual_name' in the @Column decorator. I don't know what happens if you set both columnId and the column properties with different ids.

like image 144
Uroš Anđelić Avatar answered Sep 30 '22 20:09

Uroš Anđelić


According to this GitHub thread, it seems you can also do something like this:

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

// Or
product.category = new Category().id = 1
product.save()
like image 22
Allan Juan Avatar answered Sep 30 '22 20:09

Allan Juan