Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine2.1: Finding by DiscriminatorColumn results in "Unknown field" exception

I've tried to search for this error but the fact that I haven't found anything leads me to believe that I'm doing something silly. I'll include the relevant code below, but basically I'm using multiple table inheritance (or Class Table Inheritance) and trying to use the Doctrine ORM findBy() method to query based on the discriminator column, which results in the following ORMException being thrown: "Unrecognized field: type".

Here is the code that triggers the exception:

    // $this->em is an instance of \Doctrine\ORM\EntityManager
    $repository = $this->em->getRepository('JoeCommentBundle:Thread');

    return $repository->findOneBy(array(
        'type' => $this->type,
        'related_id' => $id
    ));

Here is the relevant code for the 'base' abstract entity:

<?php

namespace Joe\Bundle\CommentBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity
 * @ORM\Table(name="comment_threads")
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn(name="type", type="string")
 * @ORM\DiscriminatorMap( {"story" = "Joe\Bundle\StoryBundle\Entity\StoryThread"} )
 */
abstract class Thread
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(name="related_id", type="integer")
     */
    protected $relatedId;

    /** MORE FIELDS BELOW.... **/

And finally, here is the code for the concrete thread entity:

<?php

namespace Joe\Bundle\StoryBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Joe\Bundle\CommentBundle\Entity\Thread as AbstractThread;

/**
 * @ORM\Entity
 * @ORM\Table(name="story_comment_threads")
 */
class StoryThread extends AbstractThread
{
    /**
     * @ORM\OneToOne(targetEntity="Story")
     * @ORM\JoinColumn(name="story_id", referencedColumnName="id")
     */
    protected $story;
}

I've double checked my schema, and the type column definitely exists, so I'm not sure what could be causing this. Any ideas? Thanks.

like image 432
RobMasters Avatar asked May 11 '12 12:05

RobMasters


1 Answers

Rob, when querying your actually using the parent entity and trying to filter on the discriminator value. Instead, work on the repository relative to the child entity you want to fetch. Doctrine will do the rest for you. So in your case you want to get the repository for StoryThread.

$repository = $this->em->getRepository('JoeCommentBundle:StoryThread');
return repository->find($id);
like image 54
Lee Davis Avatar answered Sep 17 '22 23:09

Lee Davis