Left join doctrine 2

I need to get data from 2 tables. In fact, you just need to include one field from the 2nd table in the result of the 1st table based on the form key.

I researched and found a way to do this.

$qb->select(array('a', 'c')) ->from('Sdz\BlogBundle\Entity\Article', 'a') ->leftJoin('a.comments', 'c'); 

When I implemented it, it shows the error Error: the class does not have associations with names, which are obvious, because comments are not a field of an entity table. I am confused about how to determine the second table from which to extract the field, since a.comments refers to the article table.

+5
source share
1 answer

To use Doctrine connections, you must tell Doctrine what the relationship is between your objects. This is done using relationship annotations ( @OneToOne, @OneToMany, @ManyToOne, @ManyToMany ), which you can find at http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association -mapping.html

You cannot use associations without associations in Doctrine.

According to your question, I assume that your article has a OneToMany link to the comments. Then the definition of your objects should look like:

 /** * @Entity */ class Article{ //.... all your current fields /** * @ORM\OneToMany(targetEntity="Comment", mappedBy="article") */ private $comments; //.... setters and getters } /** * @Entity */ class Comment{ //.... all your current fields /** * @ORM\ManyToOne(targetEntity="Article", inversedBy="comments") */ private $article; //.... setters and getters } 

Using these entities, you can fulfill the request.

+2
source

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


All Articles