如何在服务容器中使用Doctrine?
代码只会导致错误消息"Fatal error: Call to undefined method ...::get()“。
<?php
namespace ...\Service;
use Doctrine\ORM\EntityManager;
use ...\Entity\Header;
class dsdsf
{
protected $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public function create()
{
$id = 10;
$em = $this->get('doctrine')->getEntityManager();
$em->getRepository('...')->find($id);
}
}
services.yml
service:
site:
class: ...\Service\Site
发布于 2011-12-01 21:35:49
根据您的代码,您已经注入了一个EntityManager
。您不需要调用$em = $this->get('doctrine')->getEntityManager()
-只需使用$this->em
。
如果您还没有注入EntityManager
,请阅读this。
更新:
您需要让容器将EntityManager
注入到您的服务中。下面是一个用config.yml
实现的示例
services:
your.service:
class: YourVendor\YourBundle\Service\YourService
arguments: [ @doctrine.orm.entity_manager ]
我更喜欢在自己的services.yml
文件中使用define包的服务,但这有点高级,所以使用config.yml
已经足够好了。
发布于 2013-01-22 23:41:54
为了方便地访问Entitymanager,请使用以下方法:
//services.yml
your service here:
class: yourclasshere
arguments: [@doctrine.orm.entity_manager]
在类本身中:
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();
}
}
这是我的第一个回答,所以任何意见都是值得感谢的:)
发布于 2015-05-23 19:35:46
请尝试此代码:
$em=$this->container->get('doctrine')->getEntityManager();
$rolescheduels=$em->getRepository('OCSOCSBundle:RoleScheduel')->findByUser($user->getId());
https://stackoverflow.com/questions/8342031
复制相似问题