Conditional Relations in Symfony2

Let's say I have a Post object and a Comment object. Comment can be approved or not by the administrator (which is the flag in db). The message object has:

/** * @ORM\OneToMany(targetEntity="Comment", mappedBy="post") */ protected $comments; 

And I also need a second attribute, which will look like this:

 /** * @ORM\OneToMany(targetEntity="Comment", mappedBy="post") */ protected $approvedComments; 

How can I only upload approved comments here?

+5
source share
3 answers

Idea number 1

You can use Inheritance mapping : http://doctrine-orm.readthedocs.org/en/latest/reference/inheritance-mapping.html

The idea is to have separate classes for each type (approved and not approved), but store everything in one table ( SINGLE_TABLE inheritance).

You will need an additional column in which the discriminator of the class type will be stored.

Then you will have:

 /** * @ORM\OneToMany(targetEntity="ApprovedComment", mappedBy="post") */ protected $approvedComments; /** * @ORM\OneToMany(targetEntity="NonApprovedComment", mappedBy="post") */ protected $nonApprovedComments; 

The obvious drawback is the creation of additional classes.

Idea number 2

You can simply configure you Query / QueryBuilder as:

 `SELECT p, c FROM AcmeDemoBundle:Post p LEFT JOIN p.comments c WITH c.approved = FALSE` 

This idea seems more reasonable.

+1
source

This cannot be achieved through the relationship you described. 2 tables cannot be connected “conditionally”, since relations are based on primary keys.

Do you have at least solutions here

  • Leave the comment field in the entity with annotations, remove the annotations from the approved comments field, as this is the same as the comments understood by ORM. After that, you get the function → getComments () to get all the comments, and you could add the function "getApprovedCommentsForPost ($ post)" in your repository class to get those approved.
  • You can distinguish between comments with single inheritance, so you will have the Comment class and the ApprovedComment class in the same table, for example, you can make 2 relationships on your entity (read here doctrine-orm.readthedocs.org/en/latest/reference/inheritance- mapping.html # single-table-inheritance)
  • You can use doctrine filters to filter out unapproved comments by default when retrieving data from the comment repository.
+1
source

You cannot define this contrast in your essence. Here is the relevant documentation:

http://doctrine-orm.readthedocs.org/en/latest/reference/annotations-reference.html#annref-onetomany

As you can see, there is no choice related to conditions. You must define this condition using QueryBuilder.

0
source

Source: https://habr.com/ru/post/1208150/


All Articles