2013-02-21 4 views
0

이것이 가능한지 확실하지 않지만 쿼리에서 교리 컬렉션을 만들려고합니다. 아이디어는 일부 사전 설정 값으로 컬렉션을 채우는 것입니다. 그래서 데이터베이스를 업데이트 할 수 있습니다. 기존 시스템에서 새 시스템으로 사용자를 가져 오거나 생성하는 것처럼 생각할 수 있습니다. Im은 저장소 비트로 어려움을 겪고 있습니다. 컨트롤러와symfony2 쿼리에서 doctrine 콜렉션을 생성하십시오.

내부를 호출

엔티티

// Portal\UserBundle\Entity\User.php 

namespace Portal\UserBundle\Entity; 
use Doctrine\ORM\Mapping AS ORM; 


/** 
* @ORM\Entity 
*/ 
class User 
{ 
    /** 
    * @ORM\Id 
    * @ORM\Column(type="integer") 
    */ 
    private $id; 

    /** 
    * @ORM\Column(type="string", length=255, nullable=false) 
    */ 
    private $fistname; 

    /** 
    * Get id 
    * 
    * @return integer 
    */ 
    public function getId() 
    { 
     return $this->id; 
    } 

    // etc... 
} 

저장소

namespace Portal\UserBundle\Entity\Repository; 
use Doctrine\ORM\EntityRepository; 

class UserRepository extends EntityRepository 
{ 
    public function getGenerateNewUsers() 
    { 
    // acts as an import from an old user table 
    $sql = " SELECT firstname, surname, other FROM old_user_table "; 

    $userCollection = .... not sure how I link query? 
    return $userCollection;  

    } 
} 

는 I 상기 새로 생성 된 사용자 루프를 페치 할 수 있도록하려는 그들과 acce있다 내 엔티티 방법에 SS는

class SetupController extends Controller 
{ 
    public function indexAction(){ 

     $repository = this->getDoctrine()->getRepository('UserBundle:User'); 

     $newUsers = $repository->getGenerateUsers(); 

     // I can now have access to the users with something like 

     foreach($newUsers as $user){ 
      $user->setFirstName('testing'); 
      $user->save(); 
     } 

    } 
} 
+0

http://symfony.com/doc/current/bundles/DoctrineFixturesBundle/index.html을 보셨습니까? – cheesemacfly

+0

링크를 주셔서 감사하지만 여전히 쿼리에서 직접 교리 객체를 생성 할 수 있기를 원하십니까? 그것을하는 방법을 아는 것은 손잡이 일 것입니다. –

답변

1

그것은 일반적으로 기존의 테이블에 직접 새 매핑되지 않는이 같은 수입의 경우이다 (필드 이름, 제약 등의 측면에서) 등의 개체 및 수도 심지어 동일한 DBMS에 있지 않기 때문에 실제로 가장 좋은 옵션은 수동 방식입니다. 간단한 배열, 그들을 통해 다음 루프와 사용자를 얻을 좋아하는 구식 방법으로 기존 데이터베이스에 대해 귀하의 SQL 쿼리를 실행하고 작성 기관 :

//Set up an empty collection 
$collection = new ArrayCollection(); 

/*Assuming PDO where you have set up and executed a PDO statement $pdoStatement, 
    but mysql_fetch_assoc or whatever is appropriate for your DBMS would work equally 
    well. $oldUser should just be a plain associative array*/ 

while($oldUser = $pdoStatement->fetch(PDO::FETCH_ASSOC)){ 
    //Initialise an empty User entity 
    $newUser = new User(); 

    //Set the properties on the entity using the values from your array 
    $newUser->setFirstName($oldUser['firstname']); 
    //etc 

    //Add your user to the collection 
    $collection->add($newUser); 
} 

return $collection 

난 당신이 Usersave()를 호출 생각 통지 당신의 엔티티가 어떤 것을 상속받지 않고 특별한 방법을 가지고 있지 않은 일반 객체이기 때문에 Doctrine에서 일반적으로 그렇게 작동하지 않습니다. 엔티티를 새 데이터베이스에 저장하는 방법은 entity manager을 잡고 persist 메서드를 호출하는 것입니다. 컨트롤러에서

:로

$entityManager = $this->get('Doctrine')->getManager(); 
foreach($users as $user){ 
    //Manipulate the user here if you need to 

    //Then persist it 
    $entityManager->persist($user); 
} 

제쳐두고 - 당신은 훨씬 더 우아하고있다있는에 약간 다른 문제입니다 당신의 새로운 데이터베이스에 대해 쿼리를 실행하여 개체의 컬렉션을 얻고 싶었다 경우 해결책. Doctrine Query Language을 사용하면 개체 언어를 사용하는 동안 SQL 방식으로 데이터베이스를 쿼리 할 수 ​​있습니다. DQL을 사용하면 쿼리 결과는 기본적으로 Doctrine Entites에 hydrated이됩니다.

1

호건은 DQL을 언급합니다. 여기에 그 모습이 보이지만 이전 데이터베이스가 배선되어 있는지 확인해야합니다. 결과는 엔티티 콜렉션으로, 메소드 호출을 사용하여 데이터의 일부 또는 전체를 적절하게 저장할 수 있습니다.

namespace Portal\UserBundle\Entity\Repository; 
use Doctrine\ORM\EntityRepository; 

class UserRepository extends EntityRepository 
{ 
    public function getGenerateNewUsers() 
    { 
    $qb = $this->getEntityManager() 
       ->getRepository('Bundle:Old_User')->createQueryBuilder('o'); 
    $query = $qb->getQuery(); 
    $results = $query->getResult(); 

    return $results;  
    } 
} 
+0

좋아 보인다. 번들이란 무엇입니까? Old_User는 내가 만들어야 할 무언가입니다. 번들과 엔티티를 만들어야합니까? 건너 뛸 수 있습니까? –

+0

old_user를 현재 사용자와 함께 번들의 엔터티로 만들어야합니다. – Lighthart