core icon indicating copy to clipboard operation
core copied to clipboard

Unique constraint violation on put

Open KDederichs opened this issue 3 years ago • 1 comments

API Platform version(s) affected: 3.1.8

Description
When you try to update an API Resource that contains a doctrine collection of Entities that are not an API Resource and define a Unique Index, the update will fail since it will try to recreate the collection entities.

How to reproduce
Have like this entities:

#[Entity]
#[ApiResource]
class Foo {
 // ...
     #[OneToMany(mappedBy: 'foo', targetEntity: Bar::class, cascade: ['persist', 'remove'], orphanRemoval: true)]
    #[Valid]
    private Collection $bars;

     public function getBars(): Collection
    {
        return $this->bars;
    }

    public function setBars(Collection $bars): Foo
    {
        $this->bars = $bars;
        return $this;
    }


    public function addBar(Bar $bar): Foo
    {
        if (!$this->bars->contains($bar)) {
            $bar->foo($this);
            $this->bars->add($bar);
        }

        return $this;
    }

    public function removeBar(Bar $bar): Foo
    {
        if ($this->bars->contains($bar)) {
            $this->bars->removeElement($bar);
        }

        return $this;
    }
}

and

#[Entity]
#[UniqueConstraint(fields: ['foo', 'barType'])]
#[UniqueEntity(fields: ['foo', 'barType'])]
class Bar {
    #[ManyToOne(targetEntity: BarType::class)]
    #[JoinColumn(nullable: false, onDelete: 'CASCADE')]
    private BarType $barType;
    #[ManyToOne(targetEntity: Foo::class, inversedBy: 'bars')]
    #[JoinColumn(nullable: false, onDelete: 'CASCADE')]
    #[Ignore]
    private Foo $foo;
    private string $barVal;

//...
}

and

#[Entity]
#[ApiResource]
#[Get]
#[GetCollection]
class BarType {
//...
}

If you then try to make a PUT request with a payload that already contains a Bar

{
 "@id": "/api/foos/1"
 "@type": "Foo"
"id": 1,
 "bars": [
  {
    "barType": "/api/bar_types/1"
   "barVal": "Test"
  }
 ]
}

element it will always result in a constraint violation since it'll try to re-create the Bar

Possible Solution
Optimally Api Platform would not need to recreate the non Api Resource entities, that would fix it.

KDederichs avatar Sep 25 '23 12:09 KDederichs

Hi @KDederichs — after triage, this falls under user-misuse / HTTP semantics rather than a core bug. PUT is a replace operation per HTTP spec (RFC 9110 §9.3.4); nested items without an identifier (@id) are by design treated as new entities, and Doctrine's unique constraint then fires correctly.

Three supported ways forward, depending on what you're trying to model:

  1. Subresource on the collection. Expose Bar as an API resource (even read-only) and use /api/foos/{id}/bars to manage members individually. This is the idiomatic API Platform pattern for OneToMany collections of non-trivial children. See https://api-platform.com/docs/core/subresources/.

  2. Custom denormalizer for Bar. If you want to match existing rows by (foo, barType) instead of recreating, write a DenormalizerInterface for Bar that looks up the existing row by the unique pair before falling back to a new instance.

  3. Send @id on each nested item the user wants kept. Expose Bar (even as a read-only resource) so the client can send IRIs back; PUT will then update the existing rows instead of inserting new ones.

There's also a Doctrine flush-ordering caveat at play: with cascade: ['persist', 'remove'] + orphanRemoval: true + a unique constraint, Doctrine may INSERT before DELETE on a re-key. That's a Doctrine limitation, not specific to API Platform.

Closing as user-misuse — happy to reopen if option 1/2/3 doesn't cover your use case.

soyuka avatar Jun 04 '26 09:06 soyuka