简体   繁体   中英

TypeORM OneToMany creates column

I have three tables and entities:

  • customer
  • shop
  • shop_customer

Relation between those are:

Customer:

@OneToMany((type) => ShopCustomer, (shopCustomer) => shopCustomer.customer, { eager: false })
shopCustomer: ShopCustomer[];

Shop:

@OneToMany((type) => ShopCustomer, (shopCustomer) => shopCustomer.shop, { eager: false })
shopCustomer: ShopCustomer[];

ShopCustomer:

  @ManyToOne((type) => Customer, (customer) => customer.shopCustomer, { eager: false })
  customer: Customer;

  @ManyToOne((type) => Shop, (shop) => shop.shopCustomer, { eager: false })
  shop: Shop;

So the problem is that when I create migrations and run them, I get correct structure for shop_customer table, so:

id, customerId, shopId, Role

(Role is just a string)

The issue is with shop and customer tables. In those I get shopCustomerId columns created. Do you know what should I do in order to make it work?

Thank you for help <3

There was a caching problem. Disabling cache in ORM config file and recrating migrations resolved the issue.

It's because you have @OneToMany relations defined on Shop and Customer, so TypeOrm creates a foreign-key column to ShopCustomer.

TypeOrm many-to-one documentation specifically says "If you only care about the @ManyToOne relationship, you can define it without having @OneToMany on the related entity."

Just remove the @OneToMany relations on Shop and Customer.

The relations are ok, maybe u done the wrong relations before, try to erase de dist folder in root to erase the entities cache. As said before the @OneToMany are note needed, but is supposed they don't create any field too.

Maybe another solution is doing this code

@OneToMany((type) => ShopCustomer)
shopCustomer: ShopCustomer[];

the inverse relation in @ManyToOne are not necessary, and the eager for default is false.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM