2013-08-01 70 views

Trả lời

12

Nếu cố định của bạn thực hiện ContainerAwareInterface bạn có toàn quyền truy cập vào vùng chứa và có thể lấy một trong những người quản lý thực thể của bạn từ đó.

khi bạn có trình quản lý thực thể, bạn có thể lấy kho lưu trữ hoặc tạo truy vấn bằng DQL hoặc trình truy vấn.

namespace Vendor\YourBundleBundle\DataFixtures\ORM; 

use Doctrine\Common\DataFixtures\FixtureInterface; 
use Symfony\Component\DependencyInjection\ContainerAwareInterface; 
use Symfony\Component\DependencyInjection\ContainerInterface; 

class LoadCharacterData implements FixtureInterface, ContainerAwareInterface 
{ 
    private $container; 

    public function setContainer(ContainerInterface $container = null) 
    { 
     $this->container = $container; 
    } 

    public function load() 
    { 
     $em = $this->container->get('doctrine')->getEntityManager('default'); 

     // example using DQL 
     $query = $em->createQuery('SELECT u FROM YourBundle\Entity\User u WHERE u.name = your_name'); 
     $users = $query->getResult(); 

     // example query using repository 
     $repository = $em->getRepository('YourBundle:User'); 
     $entities = $repository->findBy(array('name' => 'your_name')); 

     // example using queryBuilder 
     $qb = $repository->createQueryBuilder('u'); 
     $qb 
      ->where('u.name = :name') 
      ->setParameter('name', 'your_name') 
      ->orderBy('u.name'); 

     $users = $qb->getQuery()->getResult(); 

     // ... 

    } 
+4

Để tham khảo trong tương lai, 'EntityManager' (thực hiện' ObjectManager') được chuyển làm đối số đầu tiên trong tải phương thức. Bạn không cần phải triển khai 'ContainerAwareInterface' –

+1

' getEntityManager() 'không được dùng nữa kể từ Symfony 2.1. Sử dụng 'getManager()' để thay thế. – marcv