I started playing with Symfony and I'm trying to create a database query. As i understand it, I should use entitymanager to create a nativequery. When I do the code below, I get this warning.
Warning: Undefined variable $entityManager
I understand that it's logical since the variable isn't initialized anywhere, but where do I get the entitymanager from?
Here is my 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();
}
}
CodePudding user response:
You are in an entity repository, _em
should be public.
You could either do:
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();
}
or use autowiring to get the entity manager.
use Doctrine\ORM\EntityManagerInterface;
public function __construct(EntityManagerInterface $em, ManagerRegistry $registry)
{
$this->em = $em;
parent::__construct($registry, News::class);
}