Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typeOrm unique row

Tags:

typeorm

nestjs

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
+----+------------+--------------+----------------------------+
like image 665
Ricardo Mendes Avatar asked Apr 22 '26 15:04

Ricardo Mendes


1 Answers

Try marking the column as Unique

@Unique() ColumnName

like image 178
Akhil Job Avatar answered Apr 25 '26 11:04

Akhil Job



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!