php 未定义方法getDoctrine

dsekswqp  于 2022-11-21  发布在  PHP
关注(0)|答案(2)|浏览(149)

我是Symfony 6的初学者,我被阻止了,因为我有一个错误消息:使用Intelephense的“未定义方法getDoctrine”
下面是我的代码:

#[Route('/recettes', name: 'app_recettes')]

    public function index(int $id): Response
    {
        $em = $this->getDoctrine()->getManager();
        $recette = $em->getRepository(Recettes::class)->findBy(['id' => $id]);

        return $this->render('recettes/index.html.twig', [
            'RecettesController' => 'RecettesController',
        ]);
    }
5m1hhzi4

5m1hhzi41#

您的控制器应该从use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;扩展到AbstractController
不应在symfony 6中使用getDoctrine()->getManager()。如果查看AbstractController中的方法,您可以看到:

trigger_deprecation('symfony/framework-bundle', '5.4', 'Method "%s()" is deprecated, inject an instance of ManagerRegistry in your controller instead.', __METHOD__);

您应该在方法或构造函数中自动连接实体管理器,然后直接使用它。

private EntityManagerInterface $entityManager;

public function __construct(EntityManagerInterface $entityManager)
{
    $this->entityManager = $entityManager;
}

#[Route('/recettes', name: 'app_recettes')]
public function index(int $id): Response
{
    $recette = $this->entityManager->getRepository(Recettes::class)->findBy(['id' => $id]);

    return $this->render('recettes/index.html.twig', [
        'RecettesController' => 'RecettesController',
    ]);
}

如果只想获取一些数据,也可以直接自动连接RecettesRepository,而不是实体管理器。
我猜您希望使用特定资源的id来显示该资源。您可能希望在您的路径中添加一些内容/{id}

#[Route('/recettes/{id}', name: 'app_recettes')]
46scxncf

46scxncf2#

迪伦的React真的很好!
如果你想fecth一个特定的recette(blog de cuisine?),你可以自动连接'recette'作为一个参数:

#[Route('/recettes/{id}', name: 'app_recettes')]
public function index(Recette $recette): Response
{
    return $this->render('recettes/index.html.twig', [
         'recette' => $recette,
     ]);

}

为此,请不要忘记安装和导入:
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Entity;

相关问题