Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/symfony/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在部分调用实体时检索该实体的实例_Php_Symfony_Doctrine - Fatal编程技术网

Php 在部分调用实体时检索该实体的实例

Php 在部分调用实体时检索该实体的实例,php,symfony,doctrine,Php,Symfony,Doctrine,我有一个页面,显示关于一部电影的信息,并提供评论。为了展示每部电影的评论,我采取了以下方式: /** *@Route(“film/{id}”,name=“film”) */ 公共功能电影(电影存储库$repo,实体管理器接口$em,请求$req,$id) { $film=$repo->find($id); $comments=$film->getComments(); $comment=新注释; $form=$this->createForm(CommentType::class); $form

我有一个页面,显示关于一部电影的信息,并提供评论。为了展示每部电影的评论,我采取了以下方式:

/**
*@Route(“film/{id}”,name=“film”)
*/
公共功能电影(电影存储库$repo,实体管理器接口$em,请求$req,$id)
{
$film=$repo->find($id);
$comments=$film->getComments();
$comment=新注释;
$form=$this->createForm(CommentType::class);
$form->handleRequest($req);
如果($form->isSubmitted()&&&$form->isValid()){
$em=$this->getDoctrine()->getManager();
$comment->setAuthor($this->getUser());
$comment->setFilm($id);
$em->persist($comment);
$em->flush();
}
返回$this->render('film/film.html.twig'[
“控制器名称”=>“FilmController”,
“胶片”=>$film,
“评论”=>[$comments],
'form'=>$form->createView()
]);
}
我认为传递$id变量(我得到的,对应于电影id)就足够了。但我得到了一个错误:

传递给App\Entity\Comment::setFilm()的参数1必须是App\Entity\Film的实例,或null,给定整数,在第61行的/home/“”/projet-film2/src/Controller/FilmController.php中调用


这个错误不言而喻,不言而喻。我必须实例化一个新的movie对象,获取其movie->getId()id,并将其作为setter参数传递。但是既然这部电影已经在这里被实例化了,那可能会使事情变得复杂,对吗除了实例化之外,还有其他方法可以解决这个问题吗?

解决方案就是注入依赖项,然后将其传递给setter:

/**
*@Route(“film/{id}”,name=“film”)
*/
公共功能胶片(胶片库$repo,胶片$film,EntityManager接口$em,请求$req,$id)
{
$filmRepo=$repo->find($id);
$comments=$filmRepo->getComments();
$comment=新注释;
$form=$this->createForm(CommentType::class,$comment);
$form->handleRequest($req);
如果($form->isSubmitted()&&&$form->isValid()){
$em=$this->getDoctrine()->getManager();
$comment->setAuthor($this->getUser());
$comment->setFilm($film);
$em->persist($comment);
$em->flush();
}
返回$this->render('film/film.html.twig'[
“控制器名称”=>“FilmController”,
“胶片”=>$film,
“评论”=>[$comments],
'form'=>$form->createView()
]);
}

您的控制器不应该包含任何逻辑。那么您的建议是什么?