Symfony、Doctrine 和 createNativeQuery

Symfony, Doctrine and createNativeQuery

我开始使用 Symfony 并尝试创建数据库查询。据我了解,我应该使用 entitymanager 来创建 nativequery。当我执行下面的代码时,我收到此警告。

Warning: Undefined variable $entityManager

我知道这是合乎逻辑的,因为变量没有在任何地方初始化,但是我从哪里得到 entitymanager?

这是我的 class:

namespace App\Repository;

use App\Entity\News;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\ORM\Query\ResultSetMapping;

class NewsRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, News::class);
    }

    public function getById($id)
    {
        $rsm = new ResultSetMapping();
            
        $query = $entityManager->createNativeQuery('SELECT * FROM `news` WHERE `id`=? LIMIT 1', $rsm);
        $query->setParameter(1, $id);
        
        $users = $query->getResult();
    }
}

您在实体存储库中,_em 应该是 public。

你可以这样做:

public function getById($id)
{
    $rsm = new ResultSetMapping();
        
    $query = $this->_em->createNativeQuery('SELECT * FROM `news` WHERE `id`=? LIMIT 1', $rsm);
    $query->setParameter(1, $id);
    
    $users = $query->getResult();
}

或使用自动装配来获取实体管理器。

use Doctrine\ORM\EntityManagerInterface;
public function __construct(EntityManagerInterface $em, ManagerRegistry $registry)
    {
        $this->em = $em;
        parent::__construct($registry, News::class);
    }