Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

It's possible, create a table without primary key in TypeOrm?

And still managing to do @OneToMany in another entity.

export class ProductsOfOrder { 
    @ManyToOne(() => Order, order => order.products)
    order: Order

    @ManyToOne(() => Product)
    product: Product

    @Column({type: 'integer'})
    amount: number
}

In the case using the foreign key of order

@Entity()
export class Order {
    @PrimaryGeneratedColumn('uuid')
    id: string

    @ManyToOne(() => User)
    user: User

    @OneToMany(() => ProductsOfOrder, productsOfOrder => productsOfOrder.order, {cascade: true})
    products: ProductsOfOrder[]
}
like image 207
Mikhail Rommulo Avatar asked Jun 08 '26 14:06

Mikhail Rommulo


2 Answers

Ciao, no you can't because its required for entities to have a primary column in terms of ORM because most of ORM operations are heavily rely on entity primary ids.

like image 138
Giovanni Esposito Avatar answered Jun 10 '26 05:06

Giovanni Esposito


Ahem, of course, you can create a table without a primary key in TypeORM.

Here's a nice dirty little hack:

  1. Add a fake primary column to your model and set the insert, select, and update options to false.
@Entity()
export class EntityWithoutPK {
  /**
  * ! This is a fake attribute
  * This is a workaround for TypeORM's `MissingPrimaryColumnError`
  **/
  @PrimaryColumn({ type: 'uuid', insert: false, select: false, update: false })
  id: never;

  // Other column definitions
}
  1. Generate a migration file and then delete the primary column part from the generated SQL

  2. Set synchronize option to false

@Entity({ synchronize: false })
export class Order
  1. Run the migration

Notes

Before applying a hack, see the following checklist. If you have a "no" for any one of them, create a primary key.

  1. You'll only query in groups, i.e. often with where condition with another indexed/FK column
  2. Individual entity doesn't make sense, you will never call a method (e.g. save) of individual entity
  3. The primary key takes a considerable amount of space for an individual record (e.g., UUID primary key for simple metrics).
  4. The entity schema doesn't change often; otherwise, the synchronize: false option might cause lots of panic.

For your case, it makes total sense to create a primary key in the order table.

like image 41
glinda93 Avatar answered Jun 10 '26 04:06

glinda93



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!