How to select discriminator column in doctrine 2

前端 未结 3 1105
长情又很酷
长情又很酷 2020-12-20 17:14

I need some help when select only discriminator column from doctrine 2 when run the DQL below

SELECT p.type FROM AppBundle\\Entity\\Product p
相关标签:
3条回答
  • 2020-12-20 17:50

    There is no direct access to the discriminator column.

    It may happen that the entities of a special type should be queried. Because there is no direct access to the discriminator column, Doctrine provides the INSTANCE OF construct.

    You can query for the type of your entity using the INSTANCE OF DQL as described in the docs. As example:

    $query = $em->createQuery("SELECT product FROM AppBundle\Entity\AbstractProduct product WHERE product  INSTANCE OF AppBundle\Entity\Product");
    $products = $query->getResult();
    

    Hope this helps

    0 讨论(0)
  • 2020-12-20 17:56

    I use this little "hack"

    1. Define a common interface for your entities (optional but recommended)
    2. Create a getType method in this interface
    3. Create constant into Discriminator entity
    4. Return the proper constant inside every discriminated entity

    That way you can retrieve the discriminator "generic" entity (Product in your case) and call getType onto it.

    Of course if you're interested into result filtering done directly by sql, this is not a solution at all and, I'm afraid, there isn't any solution available at the moment.
    If you find one better that this, please share with us.

    0 讨论(0)
  • 2020-12-20 17:56

    You should be able to do this with a scalar result with INSTANCE OF and a case, when, (else,) end clause:

    SELECT
      (case
         when p INSTANCE OF AppBundle\Entity\Product then \'0\'
         when p INSTANCE OF AppBundle\Entity\Product\SingleIssue then \'1\'
         when p INSTANCE OF AppBundle\Entity\Product\CountBasedIssue then \'2\'
         when p INSTANCE OF AppBundle\Entity\Product\TimeBasedIssue then \'3\'
         else \'foobar\'
       end) as type
    FROM
      AppBundle\Entity\Product p
    

    Of course the disadvantage is you have to update the query every time you add a DiscriminatorMap entry.

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