Question

I was used discriminator column in where clause like this:

//f = root entity
$qb = $this->createQueryBuilder('f');
$qb->add('where', 'f.format = \'image\' OR f.format = \'text\'');

I've got an error: "Message: [Semantical Error] line 0, col 73 near 'format = 'image'': Error: Class Entities\File\AbstractFile has no field or association named format"

How can i use discriminator column in where clause?

Thanks.

Was it helpful?

Solution

I think that you should use INSTANCE OF

OTHER TIPS

It would look in query builder like this:

$class = 'Entity\File\Image';

$qb = $this->createQueryBuilder('f');
$qb->where($qb->expr()->isInstanceOf('f', $class));

Note: that you will not be able to set the class as a parameter because it will be escaped.

for PHP 5.50 and above:

$this->createQueryBuilder('f')
        ->andWhere('f INSTANCE OF '.Image::class)

As this latest doctrine version it is supported to query directly the discriminator value.

public function findOfType($discr)
    {
        $qb = $this->createQueryBuilder('e');
        $qb->where('e INSTANCE OF :discr');
        $qb->setParameter('discr', $discr);
        return $qb->getQuery()->getResult();
    }

will have a result query with this clause:

WHERE e0_.discr IN ('discriminator_passed_to_function')

This doctrine extension was very useful for me because I needed to access the parent class and INSTANCE OF doesn't works in that case.

https://gist.github.com/jasonhofer/8420677

For example: I have the following class structure:

BaseClass

Class1 inherits from BaseClass (discriminator = c1)

Class2 inherits from Class1 (discriminator = c2)

Class3 inherits from Class1 (discriminator = c3)

I want to select all entities from Class1 but not from Class2 or Class3

SELECT c FROM \Class1 c WHERE TYPE(c) = 'c1';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top