Home » Php » php – Doctrine 2 – Class Table Inheritance, selecting by type

php – Doctrine 2 – Class Table Inheritance, selecting by type

Posted by: admin July 12, 2020 Leave a comment


I have two entities – News and Page.
Definition looks like this:

 * Description of Page
 * @Entity
 * @InheritanceType("JOINED")
 * @DiscriminatorColumn(name="type", type="string")
 * @DiscriminatorMap({
 *  "news" = "News" ,
 *  "page" = "Page"})
 * @table(
 *  name="pages"
 * )
class Page extends BaseEntity {...}
class News extends Page {...}

I know, how to select only “news” entities – simple SELECT ... FROM News n.

But is there some way how to select only “page” entities, which are mapped directly to Page class? Or do I have to create some extra entity extending Page for this?

How to&Answers:

The solution is to use x INSTANCE OF Entity in WHERE clause.



The solution, that I use is that I create a Switcher on the root entity Repository class, like so:

class PageRepository extends EntityRepository
  protected $_switchEntityNameSave = null;

   * @param type $fqcn 
  protected function _swapEntityDiscriminator($fqcn = null){
       $this->_switchEntityNameSave = $this->_entityName;
       $this->_entityName = $fqcn;
    } else {
       $this->_entityName = $this->_switchEntityNameSave;

  // ... AND TO USE... 

  public function findSomeStuff()
    // The query, the result in a variable, $q for example
    return $q->getQuery();


Then, in the parent classe, I do the Getter getFqcn(), like so:

abstract class BaseEntity {
   * Get fqcn
   * Fully Qualified Class Name
   * @return string
  public static function getFqcn()
      return get_called_class();
  // ...

That use the Late static binding feature and give me the full class name on the concrete object (either News or Page).

I do put abstract, to be sure to not instantiate it.

What I also add in the concrete classes, a few constants:

class News extends Page {
  const HUMAN_READABLE = "News";
  const DISCRIMINATOR = "news";   // SAME as your @DiscriminatorMap() Annotation.


That way, my Repository I can create specialized finders only on one of the types.