1
votes

I'm trying to make a Entity using typeOrm on my NestJS, and it's not working as I expected.

I have the following entity

@Entity('TableOne')
export class TableOneModel {
  @PrimaryGeneratedColumn()
  id: number

  @PrimaryColumn()
  tableTwoID: number

  @PrimaryColumn()
  tableThreeID: number

  @CreateDateColumn()
  createdAt?: Date
}

This code generate a migration that generates a table like the example below

+--------------+-------------+------+-----+----------------------+-------+
| Field        | Type        | Null | Key | Default              | Extra |
+--------------+-------------+------+-----+----------------------+-------+
| id           | int(11)     | NO   |     | NULL                 |       |
| tableTwoID   | int(11)     | NO   |     | NULL                 |       |
| tableThreeID | int(11)     | NO   |     | NULL                 |       |
| createdAt    | datetime(6) | NO   |     | CURRENT_TIMESTAMP(6) |       |
+--------------+-------------+------+-----+----------------------+-------+

That's ok, the problem is, that I want to the table only allow one row with tableTwoID and tableThreeID, what should I use in the Entity to generated the table as I expected it to be?

Expected to not allow rows like the example below

+----+------------+--------------+----------------------------+
| id | tableTwoID | tableThreeID | createdAt                  |
+----+------------+--------------+----------------------------+
|  1 |          1 |            1 | 2019-10-30 19:27:43.054844 |
|  2 |          1 |            1 | 2019-10-30 19:27:43.819174 |    <- should not allow the insert of this row
+----+------------+--------------+----------------------------+
2

2 Answers

5
votes

Try marking the column as Unique

@Unique() ColumnName

3
votes

This is currently expected behavior from TypeORM. According to the documentation if you have multiple @PrimaryColumn() decorators you create a composite key. The combination of the composite key columns must be unique (in your above '1' + '1' + '1' = '111' vs '2' + '1' + '1' = '211'). If you are looking to make each column unique along with being a composite primary key, you should be able to do something like @PrimaryColumn({ unique: true })