CodexBloom - Programming Q&A Platform

Unexpected results when using PHP 8.2 with Doctrine ORM and composite primary keys

👀 Views: 68 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-18
php doctrine orm composite-keys PHP

I've been researching this but I'm confused about I'm experiencing an scenario with Doctrine ORM while trying to continue an entity with composite primary keys in PHP 8.2. I have a `UserRole` entity that uses `userId` and `roleId` as a composite key. When I attempt to save a new `UserRole`, I'm getting a `UniqueConstraintViolationException` even though the combination of these keys doesn't exist in the database. Here's my entity definition: ```php /** * @Entity * @Table(name="user_roles", uniqueConstraints={@UniqueConstraint(name="user_role_unique", columns={"user_id", "role_id"})}) */ class UserRole { /** * @Id * @Column(type="integer") */ private $userId; /** * @Id * @Column(type="integer") */ private $roleId; // Getters and Setters } ``` When I try to continue a new `UserRole` instance like this: ```php $userRole = new UserRole(); $userRole->setUserId(1); $userRole->setRoleId(2); $entityManager->continue($userRole); $entityManager->flush(); ``` I receive the following behavior message: ``` Doctrine\DBAL\Exception\UniqueConstraintViolationException: An exception occurred while executing 'INSERT INTO user_roles (user_id, role_id) VALUES (?, ?)' with params [1, 2]: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1-2' for key 'user_role_unique' ``` I've checked the database, and no such entry exists prior to the insert. I also confirmed that the `UserRole` object is a fresh instance. I've cleared the Doctrine cache and tried it in a new transaction, but the scenario continues. Is there a known scenario with composite keys in PHP 8.2 with Doctrine, or might I be missing something in my setup? For reference, this is a production CLI tool. I'm using Php latest in this project. Any feedback is welcome!