Search code examples
symfonydoctrine-ormsingle-table-inheritance

How to get a mixed object types resultset from Doctrine2 Single Table Inheritance repository?


For the following schema:

Animal - age - gender - size

Cat extends Animal - fur_color

Snake extends Animal - scales_color

Elephant extends Animal - tusks_size

When I do $em->getRepository('AcmeDemoBundle:Animal')->findAll() I will recieve a collection on Animal objects without their subclass properties.

When I do $em->getRepository('AcmeDemoBundle:Cat')->findAll() I will recieve the objects with their subclass (Cat) properties, however I will get only Cat objects (no snakes or elephants).

1) Is there I way to get all the animals, but not as base Animal objects, but actually their leaf subclass type?

Eg. for database like this:

Animals table:

ID  | discr | age | gender | size | fur_color | scales_color | tusks_size
1   | snake | 2   | male   | 20ft | NULL      | green        | NULL
2   | cat   | 3   | female | 5ft  | red       | NULL         | NULL
3   | eleph | 6   | male   | 99ft | NULL      | NULL         | 40ft.
4   | cat   | 2   | male   | 6ft  | grey      | NULL         | NULL

I'd like to recieve a Collection of:

  • Snake (id: 1, age: 2, gender: male, size: 20ft, scales_color: green)
  • Cat (id: 2, age: 3, gender: female, size: 5ft, fur_color: red)
  • Elephant (id: 3, age: 6, gender: female, size: 99ft, tusks_Size: 40ft.)
  • Cat (id: 4, age: 2, gender: male, fur_color: grey)

2) If it's not possible with STI... is it possible with Class Table Inheritance?


Solution

  • Indeed it seems I had some error in my configuration. Recreating the bundle and writing the entities again fixed the problem as @Bez and @Cerad suggested.