Skip to content

Many-to-many gives error ER_DUP_ENTRY everytime I save. This one also related to inverseJoinColumn. #5704

@ouspheaktra

Description

@ouspheaktra

Issue type:

[x ] bug report

Database system/driver:

[x] mysql / mariadb

TypeORM version:

[x] latest

Steps to reproduce or a small repository showing the problem:

@Entity()
export class Tag {

  @PrimaryGeneratedColumn()
  id: number;

  @PrimaryColumn()
  title: string;

  @ManyToMany(() => Article, article => article.tags)
  articles: Article[]

}

// ---

@Entity()
export class Article {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  title: string;

  @ManyToMany(() => Tag, tag => tag.articles)
  // if no inverseJoinColumn here, it works fine but I need it
  // because in Tag, there are 2 primary columns but I only need one, here.
  @JoinTable({
    inverseJoinColumn: {
      referencedColumnName: 'id'
    }
  })
  tags: Tag[]

}

// ---

createConnection().then(async conn => {

    /* FAKE DATA , uncomment this if u need a fake data
    const article = new Article();
    article.title = 'test'
    const tag = new Tag();
    tag.title = 't';
    await conn.manager.save(tag)
    article.tags = [tag]
    await conn.manager.save(article)
    /* --- */

    const articleRepo = conn.getRepository(Article)
    const one = await articleRepo.findOne(1, { relations: ['tags'] });
    // no error if no load 'tags'
    // I'm not doing any editing, but it still produces error
    await articleRepo.save(one)

    await conn.close()
    console.log('herer')

}).catch(error => console.log(error));

This is the error:

ER_DUP_ENTRY: Duplicate entry '1-1' for key 'PRIMARY'`.

After I look at SQL, I see:

INSERT INTO `article_tags_tag`(`articleId`, `tagId`) VALUES (?, ?) -- PARAMETERS: [1,1]

There shouldn't be any error because I didn't do any editing at all.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions