2

I have two entites in a ManyToOne relationship:

A *-->1 B

B has a function:

public addA(A $item) {
    $this->As[] = $item
}

the problem is that it is possible to add the same instance of A several times to an instane of B, and doing so even one extra time results in a primary key constraint error in the join table.

I know that I could solve this by simply checking if the A instance is already bound to the instance of B before adding it, but is there any way to achieve this same functionality natively in Doctrine? I.e., can I get doctrine to ignore an insertion if it would lead to a duplicate value in a relation?

csvan
  • 8,782
  • 12
  • 48
  • 91

1 Answers1

0

Doctrine's indexed associations allow you to index a relationship array by primary key, which will guarantee that you won't end up with duplicates when you're adding items.

/**
 * @OneToMany(targetEntity="A", mappedBy="B", indexBy="primary_key_of_a")
 **/
private $As;

public addA(A $item) {
    $this->As[$item->getPrimaryKey()] = $item
}

Update

Although the answer above will guarantee that each relation will exist only once, doctrine may delete/reinsert an existing relation depending on how it was added. For more info on how to make doctrine add/delete relations to/from the db only as needed see my answer here.

Community
  • 1
  • 1
FuzzyTree
  • 32,014
  • 3
  • 54
  • 85