Let's say I have a Post entity, and a Comment entity. A comment can be approved or not by an admin (which is a flag in the db). The post entity has:
/**
* @ORM\OneToMany(targetEntity="Comment", mappedBy="post")
*/
protected $comments;
And I also want a second attribute which will look like:
/**
* @ORM\OneToMany(targetEntity="Comment", mappedBy="post")
*/
protected $approvedComments;
How is it possible to load only the approved comments here?
You could use Inheritance mapping
: https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/inheritance-mapping.html
The idea would to have separate classes for each type (approved and non-approved), but to store everything in a single table (SINGLE_TABLE
inheritance).
You will need to have additional column which will store class type discriminator.
Then, you would have:
/**
* @ORM\OneToMany(targetEntity="ApprovedComment", mappedBy="post")
*/
protected $approvedComments;
/**
* @ORM\OneToMany(targetEntity="NonApprovedComment", mappedBy="post")
*/
protected $nonApprovedComments;
The obvious downside is creation of additional classes.
You could just tweak you Query
/QueryBuilder
like:
`SELECT p, c FROM AcmeDemoBundle:Post p LEFT JOIN p.comments c WITH c.approved = FALSE`
This idea seems more reasonable.
This can not be achieved through relationships as you describe it. 2 tables can not be related "conditionally" as the relations are based on primary keys.
You have at least solutions here
You cannot define that contraint in your entity. Here is the related documentation:
http://doctrine-orm.readthedocs.org/en/latest/reference/annotations-reference.html#annref-onetomany
As you can see there is no option which is related to conditions. You have to define this condition using QueryBuilder.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With