Skip to content
Advertisement

Retrieve a given selection based on a linked table field

I’m beginner at Symfony (use SF5). have a comments table, inside which is a filmId column, which is of type relation with the primary id of, you can imagine, the film table. For the moment I get a film on a page according to its id, and get all the comments, no matter the id of the film:

/**
 * @Route("/user/film/{id}", name="film")
 */
public function film(FilmRepository $repo, CommentRepository $comRepo, EntityManagerInterface $em, Request $req, $id)
{
 $film = $repo->find($id);

 $comments = $comRepo->findAll();
 dump($comments);



 return $this->render('film/film.html.twig', [
     'controller_name' => 'FilmController',
     'film' => $film,
     'comments' => $comments
 ]);
}

I dump() $comments to find out a little more. It returns to me that filmId is of type PersistentCollection. I would like to retrieve the comments specific to each film according to filmId.

I tried to retrieve them by a $comments = $comRepo-> findBy($id) (since the id of the film I get in GET is what I want for the filmId), it gives me a nice unrecognized field error.

Following the documentation, I tried to create a custom query like this:

//CommentRepository
public function findAllWithFilmId($filmId) 
    {
        $em = $this->getEntityManager();

        $query = $em->createQuery(
            'SELECT c
            FROM AppEntityComment c
            WHERE c.filmId = :filmId'
        )->setParameter('filmId', $filmId);

        return $query->getResult();
    }
//FilmController
 $filmId = $id;
 $comments = $this->getDoctrine()
    ->getRepository(Comment::class)
    ->findAllWithFilmId($filmId);

But I get the following error:

[Semantical Error] line 0, col 67 near ‘filmId =: fi’: Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected.

What’s wrong ? When is filmId defined as :fi? And how to create a correct request according to the filmId?

Advertisement

Answer

The first error $comments = $comRepo-> findBy($id) is beacuse when calling findBy you need to send an array. Documentation

In your case, you want to find by Id so it should be as following:

$comments = $comRepo->findBy(array('id' => $id));

Also you can call findById which expects only the id parameter.

$comments = $comRepo->findById($id);

Note: as @El_Vanja said, you can use the QueryBuilder, but IMO it is unnecesary for a simple query llike this one.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement