Doctrine Class Table Inheritance get all children

2.8k views Asked by At

I want to get all the articles, and get the type of the article (discriminator). Maybe there is another way to combinate all children (all records of fixed and auction) and sort them on creation date?

Article Entity:

/**
 * Article
 *
 * @ORM\Table("articles")
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn(name="article_type", type="string")
 * @ORM\DiscriminatorMap({"auction" = "Auction", "fixed" = "Fixed", "tba" = "TBA"})
 */
class Article
{

Auction Entity

/**
 * Auction
 *
 * @ORM\Table("auction")
 * @ORM\Entity
 */
class Auction extends Article
{
...

Fixed entity

/**
 * Fixed
 *
 * @ORM\Table("fixed")
 * @ORM\Entity
 */
class Fixed extends Article
{
    ...
1

There are 1 answers

0
João Alves On BEST ANSWER

1 - Create a repository for your Article Entity and add a method that return all Articles(off course you can use all methods available by Doctrine2, find, findAll ...). In order to order your entity by the date of the creation you must have that property on your Article Entity( this property will be used for both Child, and must be on your Article Entity, witch makes sense)

class Article {

    /**
     * @var \DateTime
     * 
     * @ORM\Column(name="created_at", type="datetime")
     * 
     */
    protected $createdAt
}

class ArticleRepository extends EntityRepository{

 public function getAll() {

    try {

        $qb = $this->getEntityManager()->createQueryBuilder();

        $qb->select('a')
           ->from('bundleName:Article', 'a');

        $qb->orderBy('a.createdAt', 'DESC');

         return $qb->getQuery()->getResult();

       } catch (\Doctrine\ORM\NoResultException $e) {
           return array();
       } catch (\Exception $e) {
           return array();
       }
}

On your controller in order to check the type of your article you can do:

$entities = $em->getRepository('bundleName:Article')->getAll();

foreach(entities as $entity){

  if($entity instanceof Fixed){
    // do what you want
  }elseif($entity instanceof Auction){

  }
}