Doctrine 2 - How to use discriminator column in where clause

后端 未结 5 1740
春和景丽
春和景丽 2020-12-14 05:45

I was used discriminator column in where clause like this:

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


        
相关标签:
5条回答
  • 2020-12-14 06:20

    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.

    0 讨论(0)
  • 2020-12-14 06:25

    for PHP 5.50 and above:

    $this->createQueryBuilder('f')
            ->andWhere('f INSTANCE OF '.Image::class)
    
    0 讨论(0)
  • 2020-12-14 06:28

    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')
    
    0 讨论(0)
  • 2020-12-14 06:41

    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';
    
    0 讨论(0)
  • 2020-12-14 06:43

    I think that you should use INSTANCE OF

    0 讨论(0)
提交回复
热议问题