Doctrine 2 - How to use discriminator column in where clause

随声附和 提交于 2019-11-30 12:26:43

问题


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.


回答1:


I think that you should use INSTANCE OF




回答2:


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.




回答3:


for PHP 5.50 and above:

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



回答4:


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')



回答5:


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';


来源:https://stackoverflow.com/questions/5988636/doctrine-2-how-to-use-discriminator-column-in-where-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!