typeorm: Constraint unique for relations problem

Issue type:

[x] question [x] bug report [ ] feature request [ ] documentation issue

Database system/driver:

[x] postgres

TypeORM version:

[ ] latest [x] @next

Description:

I have an entity

@OneToOne(type => Ent, ent => ent.auction, {
    cascade: ['insert', 'update']
  })
  @JoinColumn()
  ent: Ent;

and i got error QueryFailedError: duplicate key value violates unique constraint "REL_daf24ebe8d9c365f317d5f1983" because relation column is unique.

Why did you begin to add unique for relation columns? How can i remove unique option?

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Reactions: 10
  • Comments: 15 (4 by maintainers)

Most upvoted comments

Correct, we added unique since one-to-one means that this entity has a relation with only ONE another relation, which means both sides of relations are unique. Im sure you have this issue because you should use many-to-one for your use case.

So I ran into this issue as well and it really bugged me out. I came to the realization, that the JoinColumn annoation was at the wrong side in my case.

I had

class User {
  @OneToOne(type => Photo, p => p.user })
  @JoinColumn() // <------- produced the error
  photo: Photo;
}
class Photo {
  @OneToOne(type => User, u => u.photo })
  user: User;
}

And that helped:

class User {
  @OneToOne(type => Photo, p => p.user })
  photo: Photo;
}
class Photo {
  @OneToOne(type => User, u => u.photo })
  @JoinColumn() // <------- works
  user: User;
}

But It might be a different case but in our case the userId was a column in the photo table. So that worked for us 😃

@pleerock Can there be a problem with saving call (cascades & just ent save) at one time? one-to-many not resolve this problem.

auctionsService.save(newAuction) ---check exist---->save ent------>save auction
this.entsService.save(newEnt) ------check exist--------->(error)-->not update ent

@ayaankhan98 You don’t need to have 2 different relation cardinalities. You are describing a 1:N relationship between roles and users. 1 role might have N users, but N users only can have 1 role. In this case, the PK of role should then go as an FK to user. This way, a User can only have 1 role (specified by the FK role_id) and N users can have this same role associated without problems.

In the User entity you should put ManyToOne relation referencing role and keep OneToMany in Role entity referencing users.