Can the discriminator mapping strings of a Doctrine entity be fetched from a database foreign table field? If not, how to handle inheritance type mapping in such a situation?
Considering a Doctrine 2.7.2 abstract entity Person
with concrete entities A
and B
like:
/**
* @MappedSuperclass
* @Table(name="PERSON")
*/
abstract class Person {
/**
* @Id
* @GeneratedValue
*/
protected $id;
/**
* @Column(name="name",type="string")
*/
protected $name;
/**
* @OneToOne(targetEntity="PersonType")
* @JoinColumn(name="type", referencedColumnName="id")
*/
protected $type;
}
/**
* @Entity
* @Table(name="PERSON")
*/
class A extends Person {}
/**
* @Entity
* @Table(name="PERSON")
*/
class B extends Person {}
A Person
has a type bound to a PersonType
entity like:
/**
* @Entity
* @Table(name="PERSON_TYPE")
*/
class PersonType {
/**
* @Id
* @GeneratedValue
*/
protected $id;
/**
* @Column(name="code",type="string")
*/
protected $code;
/**
* @Column(name="name",type="string")
*/
protected $name;
}
How to get the right class instantiated by repository query methods like find()
, findBy()
, findById()
, etc?
Database set:
SELECT * FROM PERSON:
id name type
1 John 1
2 Tom 2
SELECT * FROM PERSON_TYPE:
id code name
1 A Type A
2 B Type B
Expected results:
$entityManager->getRepository("A")->findOneById(2); // null
$entityManager->getRepository("B")->findOneById(2); // B object (Tom)
$entityManager->getRepository("A")->findOneById(1); // A object (John)
I can't find how to specify this using a discriminator.
Alternatively I have a working solution implementing a SQLFilter with the inconvenience to have to enable or disable filter.
An alternative solution may be to populate $discr?
(I can of course use the Person::findByType()
method but it would be nice to have this feature directly managed by the respective repositories).