sqlsymfonycreatequery

Symfony createQuery winth multiple table


I would like to recover the user who wrote the post, only I have an error when I try to do it "Attempted to call an undefined method named "getIdPost" of class "App\Entity\User"."

$em = $this->getDoctrine()->getManager();
                $query = $em->createQuery( //creation de la requête
                    'SELECT p , u
                    FROM App\Entity\User u, App\Entity\Post p
                    WHERE p.Id_Post_Parent IS NULL
                    AND p.Id_User = u.idUser
                    ORDER BY p.Post_Date_Time DESC'
                )->setMaxResults(10);
                $posts = $query->getResult();

                $publicPosts = array();
                $comments = array();
                for($i = 0; $i<sizeof($posts) ; $i++){
                    $publicPosts[$i] = $posts[$i]->getArray();
                    //récupération des commentaires
                    $em = $this->getDoctrine()->getManager(); //on appelle Doctrine
                    $query = $em->createQuery( //creation de la requête
                        'SELECT p , u
                        FROM App\Entity\User u, App\Entity\Post p
                        WHERE p.Id_Post_Parent = :idParent
                        AND p.Id_User = u.idUser'
                    )->setParameter('idParent', $posts[$i]->getIdPost())
                    ->setMaxResults(10); //On limite à 10 commentaires par posts
                    $comments[$i] = $query->getResult(); //variable qui récupère la requête
                }

If I remove the User entity of the query it works and I have no error ... I do not understand what it's due, why it tells me that there is no method "getIdPost" in user? This is normal since it is a method of "Post" :x


Solution

  • you would like the user who wrote the post it's a bit weird to get it from a query don't you have a $post->getUser() ? I think you should join the table to acheive that

           $query = $em->createQuery( //creation de la requête
               'SELECT u
                FROM App\Entity\User u, 
                LEFT JOIN App\Entity\Post p on p.Id_User = u.idUser
                WHERE p.Id_Post_Parent IS NULL
                ORDER BY p.Post_Date_Time DESC'
            )->setMaxResults(10);