2013-06-25 1 views
7

Doctrine ORM (2.3, PHP> 5.4)과 함께 ArrayCollection을 사용하고 객체 값을 (예 : set 메서드를 사용할 때) 컬렉션의 키와 연결할 때마다 값이 올바르게 저장됩니다 데이터베이스에. 그러나 엔터티에서 컬렉션을 검색하려면 키가 검색되지 않고 대신 숫자 인덱스가 사용됩니다. 예를 들어Doctrine - Store ArrayCollection keys

, 나는 다음과 같은 클래스가있는 경우 :

/** @Entity */ 
class MyEntity 
{ 
    /** @OneToMany(targetEntity="MyOtherEntity", mappedBy="mainEntity") */ 
    private $myArray; 

    public function __construct() 
    { 
     $this->myArray = new ArrayCollection(); 
    } 

    public function addOtherEntity($key, $value) 
    { 
     $this->myArray->set($key, $value); 
    } 

    ... 
} 

/** @Entity */ 
class MyOtherEntity 
{ 
    /** @ManyToOne(targetEntity="MyEntity", inversedBy="myArray") */ 
    private $mainEntity; 
    ... 
} 

set 방법이 제대로 작동하지만 내가 $myArray의 정보를 키를 검색 할 때 사라졌다.

어떻게하면 ORM이 키를 올바르게 기억하게 할 수 있습니까? 미리 감사드립니다.

답변

5

이것은 다음과 같은 방법으로 해결 : 제대로 키를 저장할 수 있도록 당신은 또한 당신의 DB 스키마에 MyOtherTable_Key 필요

/** @Entity */ 
class MyEntity 
{ 
    /** @OneToMany(targetEntity="MyOtherEntity", mappedBy="mainEntity", indexBy="key") */ 
    private $myArray; 

    public function __construct() 
    { 
     $this->myArray = new ArrayCollection(); 
    } 

    public function addOtherEntity($key, $value) 
    { 
     $this->myArray->set($key, $value); 
    } 

    ... 
} 

/** @Entity */ 
class MyOtherEntity 
{ 
    /** @ManyToOne(targetEntity="MyEntity", inversedBy="myArray") */ 
    private $mainEntity; 

    /** @Column(name="MyOtherTable_Key", type="string", unique=true, length=50) 
    private $key; 
    ... 
} 

.

항상 개체 키를 속성에 설정해야합니다. 이렇게하는 한 가지 방법은 생성자에서 키를 선언하는 것입니다.

public function __construct($key) 
{ 
    $this->key = $key; 
} 
+0

응답을 키 생성하는 솔루션입니다. –

+0

http://doctrine-orm.readthedocs.org/ko/latest/tutorials/working-with-indexed-associations.html –

+0

응답을 기다리시겠습니까? 질문 하나? –