Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Left join in doctrine 2

I need to fetch data from 2 tables. Actually just need to include one field from 2nd table into result of 1st table on basis of form key.

I did research and find 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 error Error: Class has no association named comments which is obvious thing because comments is not a field of Article table (entity). I am confused how to define 2nd table from which field needs to fetched, as a.comments is relates of Article table.

like image 243
Davinder Kumar Avatar asked Oct 30 '22 01:10

Davinder Kumar


1 Answers

To use Doctrine's joins you must tell Doctrine what is the relation between your entities. This is done using the relationship annotations (@OneToOne, @OneToMany, @ManyToOne, @ManyToMany) that you can find in http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html

You can't use joins without associations in Doctrine.

According to your question, I assume that your Article entity has a OneToMany relationship with Comments. Then, your entities definition should be similar to:

/**
 * @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'll be able to execute the query.

like image 186
Oscar Pérez Avatar answered Nov 15 '22 07:11

Oscar Pérez