Sunday, December 10, 2023

Doctrine error Binding entities to query parameters only allowed for entities that have an identifier

If you have reached this page you are probably a little bit desperate to know WHY?!!! After checking doctrine mappings for a while I've solved the mystery.  In my case it was quite easy and stupid:

1. In some command I would create a new instance of MyClass() which has an autoid generated primary key called $id. 

2. At some point I would pass it to some repository function:  $this->em->searchForMyObject($myNewObject);

3. The repository function would look like:

public function  searchForMyObject(MyClass $object): ?SomeOtherClass

{

     $result = $this->createQueryBuilder('o')

            ->select('o')
->where('o.my_property = :object')
....

}


4. Reason for the error: the object was not persisted to database or retrieved from database, so it had no actual id value.

Reading the error again, now it makes sense:   "entities that have an identifier.".