2012-09-23 5 views
2
/** @Entity */ 
class First 
{ 
    /** @OneToMany(targetEntity="Second", mappedBy="parent") */ 
    protected $secondList; 

    // access methods here 
    public function __construct() 
    { 
     $this->secondList = new ArrayCollection(); 
    } 
} 

/** @Entity */ 
class Second 
{ 
    /** 
    * @ManyToOne(targetEntity="First", inversedBy="secondList") 
    * @JoinColumn(name="First_id", referencedColumnName="Id") 
    */ 
    protected $parent; 
} 

Second 클래스에서 ArrayCollection $secondList 요소로 복용의 문제입니다. Second ManyToOne 관계가 올바르게 작동하고 있습니다. 아마도 나는 지속성을 초기화하는데 뭔가 잘못을했습니다. 왜냐하면 SQL베이스의 First_Id은 항상 null이기 때문입니다.교리 2 : OneToMany 관계 여기

$first = new Second(); 
$second = new First(); 
$first->getSecond()->add($second); 
$em->persist($second); 
$em->persist($first); 

어떤 제안이?

답변

1

Doctrine2 docs이 말. $first->secondList 속성에 cascade={"persist"} 옵션을 추가 할 수 있습니다.

+0

자, 두 번째 테이블 레코드에서 First_Id 열을 설정하는 데 정말 도움이됩니다. 그러나 First 클래스 객체를 가져 오려고하면 Second를 'ArrayCollection'으로 가져 가지 않습니다. 비어있는 컬렉션 만 있습니다 : | –

+0

db에서 모든 것이 정상입니까? 그걸 어떻게 가져 왔니? 네가 가진 것을 어떻게 확인하고 있니? 왜냐하면 $ first-> getSecond()를 호출 할 때 그것을로드해야하기 때문입니다. – Pinetree

+0

그리고 실제로 그렇게하고 있습니다. DB는 괜찮습니다 (결국 스키마는 doctrine tool-kit에 의해 생성되었습니다). 나는'EntityManager' 클래스에서 find() 나 getRepository() 메소드를 사용하여 객체를 얻는다. 객체가 제대로 생성되었습니다. 심지어'Second' 클래스 객체 만 얻었습니다. 저는'First' 관련 클래스 객체와 완전한 관계가 있습니다. 오, 내가'serialize ($ first-> getSecondList() -> current())'를 사용하여 그 목록을 검사하면,'$ takedSecond-> getSomeOtherValue()'에 의해 물건을 가져가는 것은 객체가 아닌 변수에서 method를 사용하는 동안의 오류를 보여줍니다. –

1

퍼스트 클래스에서 괄호를 닫아야합니다. 그게 문제가 아닌 경우

/** @OneToMany(targetEntity = "Second", mappedBy = "parent") */ 

- 오류 메시지가?

In the case of bi-directional associations you have to update the fields on both sides: 

이 당신이 좋아하는 무언가를해야한다는 것을 의미 :

$second->setParent($first); 

$second 외부 키를 가지고

+0

오, 티포. 오류 메시지는 없지만 두 번째 전에 캐스케이드 매핑 (some attribute, 나는 havent이 doctrine references에서 neccessary를 사용하는 것으로 밝혀졌다.)을 사용하는 것에 대한 오류가있다. –

+0

캐스케이드 버그의 경우 OneToMany 관계에 추가하십시오 :'cascade = { "persist"}'다른 문제가 무엇인지 확실하지 않습니다 ... 모든 것이 데이터베이스에 저장됩니까? – mbinette