Symfony2 Use Doctrine in Service Container
Solution 1:
According to your code, you already have an EntityManager
injected. You don't need to call $em = $this->get('doctrine')->getEntityManager()
— just use $this->em
.
If you don't inject an EntityManager
already, read this.
UPDATE:
You need to make the container inject an EntityManager
into your service. Here's an example of doing it in config.yml
:
services:
your.service:
class: YourVendor\YourBundle\Service\YourService
arguments: [ @doctrine.orm.entity_manager ]
I prefer to define bundles' services in their own services.yml
files, but that's a bit more advanced, so using config.yml
is good enough to get started.
Solution 2:
For easily accessing the Entitymanager use the following one:
//services.yml
your service here:
class: yourclasshere
arguments: [@doctrine.orm.entity_manager]
And in the class itself:
class foo
{
protected $em;
public function __construct(\Doctrine\ORM\EntityManager $em)
{
$this->em = $em;
}
public function bar()
{
//Do the Database stuff
$query = $this->em->createQueryBuilder();
//Your Query goes here
$result = $query->getResult();
}
}
This is my first answer so any comments are appreciated :)
Solution 3:
Please try this code:
$em=$this->container->get('doctrine')->getEntityManager();
$rolescheduels=$em->getRepository('OCSOCSBundle:RoleScheduel')->findByUser($user->getId());