Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select entities of multiple subclasses extending from one superclass using doctrine 2

Given this setup for my Doctrine 2 Entities:

App\Bundle\LorumBundle\Entity\Node:
  type: entity
  table: node
  fields:
    id:
      id: true
      type: integer
      unsigned: false
      nullable: false
      generator:
        strategy: IDENTITY

    created:
      type: datetime

  inheritanceType: SINGLE_TABLE

  discriminatorColumn:
    name: type
    type:  string
    length: 255
  discriminatorMap:
    a: a
    b: b
    c: c

App\Bundle\LorumBundle\Entity\A:
  type: entity

  fields:
    status:
      type: boolean

App\Bundle\LorumBundle\Entity\B:
  type: entity

  fields:
    status:
      type: boolean

App\Bundle\LorumBundle\Entity\C:
  type: entity

  fields:
    title:
      type: string

Now what I want to get is basically a mixed list of Entities of the type A & B (not C) with the status == true.

I could write a Query like this - using the instance ofoperator to limit the result to the subclasses i want of course but i will get an Error because the property I want to match against (status) is not mapped in the Superclass even tough all the Entities i want to match against have it:

$queryBuilder->select('Node');
$queryBuilder->from('App\Bundle\LorumBundle\Entity\Node','Node');
$queryBuilder->add('where',$queryBuilder->expr()->orx(
        'Offer INSTANCE OF AppLorumBundle:A',
        'Offer INSTANCE OF AppLorumBundle:B'
));
$queryBuilder->where($queryBuilder->expr()->eq('Node.status', '?1'));
$queryBuilder->setParameter(1, true);
$queryBuilder->orderBy('Node.created', 'asc');
$queryBuilder->setFirstResult( 0 );
$queryBuilder->setMaxResults( 200 );

Is there any way to do this, short of writing your own persister and hack it into Doctrine2?

Unfortunately its not an Option for me to just add the Information to the Superclass (in my real scenario this situation mostly applies to relations which i don't want to be loaded eagerly with every subclass)

like image 690
Hannes Avatar asked Nov 13 '22 09:11

Hannes


1 Answers

You can use UNION and work with queries for entities A and B

  • build query for entity A
  • build query for entity B
  • build query for limit and order using UNION for queries A and B

no need to do any hacks for Doctrine library

like image 115
WizardZ Avatar answered Nov 16 '22 02:11

WizardZ