简体   繁体   中英

How to make unique constraint on ONE to MANY relationship?

I have two entities: project and actor .

export abstract class BaseEntityModel {
  @PrimaryGeneratedColumn()
  id: number;
}

@Entity()
export class Project extends BaseEntityModel {
    @Column()
    title: string;

    @OneToMany(type => Actor, actor => actor.project)
    @JoinColumn()
    actors: Actor[];
}

@Entity()
export class Actor extends BaseEntityModel {
    @Column({unique: true}) 
    title: string;

    @ManyToOne(type => Project, project => project.actors)
    project: Project;
}

I want unique actor title per project, but not across database.

OK

projects: [
  {
    title: "webapp",
    actors: [
      {
        title: "dev"
      }
    ]
  },
  {
    title: "json-parser",
    actors: [
      {
        title: "dev"
      },
      {
        title: "target"
      }
    ]
  }
]

NOT OK

projects: [
  {
    title: "webapp",
    actors: [
      {
        title: "dev"
      },
      {
        title: "dev"
      }
    ]
  },
  {
    title: "json-parser",
    actors: [
      {
        title: "dev"
      },
      {
        title: "target"
      }
    ]
  }
]

@Column({unique: true}) work as unique across table, that is not what I want. There is also class decorator @Unique(['title']) , but it seems to be doing the same.

Is there something from TypeORM that I can use, or do I have to check myself if the actor.title already exist in project. To avoid duplicated actor.title in the same project. While keeping the possibility to have multiple time the same actor.title across the database?

Note that Actor entity should not be shared across projects (no many to many relationship).

@Unique(['title', 'project'])类装饰器添加到Actor似乎是我想要的,请注意,我以某种方式“破坏了”数据库,并且只有在删除/创建数据库后,迁移才能正常工作。

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