Search code examples
symfonydoctrine-ormsymfony-3.3

Doctrine selected joined objects


I have two two related entery (class): First class (Todo class):

class Todo
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;
}

And Comment class(part):

class Comment
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * ID человека
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Todo")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="postid", referencedColumnName="id")
     * })
     */
    private $postId;
}

How I can select comment's by Todo id?

In Controller I try :

$todos=$this->getDoctrine()
    ->getRepository('AppBundle:Todo')
    ->find($id);
//   var_dump($todos);
$em=$this->getDoctrine()->getManager();
$comments=$em->createQueryBuilder()
    ->select('c')
    ->from('Comment','c')
    ->leftJoin('')
    ->where('postid',':postID')
    ->orderBy('postid', 'ASC')
     ->setParameter('postID', $id)
     ->getQuery()
     ->getResult();

How to choose Comment on the connection with Todo?


Solution

  • Perhaps these changes will do what you want:

    class Comment
    {
        /**
         * @var int
         *
         * @ORM\Column(name="id", type="integer")
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        private $id;
    
        /**
         * ID человека
         * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Todo")
         * @ORM\JoinColumns({
         *   @ORM\JoinColumn(name="postid", referencedColumnName="id")
         * })
         */
        private $post;
    }
    

    and...

    $todos = $this->getDoctrine()
        ->getRepository('AppBundle:Todo')
        ->find($id);
    
    $em = $this->getDoctrine()->getManager();
    $comments = $em->createQueryBuilder()
        ->select('c')
        ->from('Comment', 'c')
        ->leftJoin('AppBundle:Todo', 't')
        ->where('c.post = :todo')
        ->orderBy('post', 'ASC')
        ->setParameter('todo', $todos)
        ->getQuery()
        ->getResult();