2015-01-31 3 views
10

주어진 값이 에 있는지 확인하려면 어떻게해야합니까? Doctrine Collection (ManyToMany 관계) 필드가 있습니까?Doctrine2 : Doctrine 컬렉션에 존재하는 값이 있는지 확인하십시오.

예를 들어 내가하려고 :

$someClass = $this-> 
      getDoctrine()-> 
      getRepository('MyBundle:MyClass')-> 
      find($id); 

if (!$entity->getMyCollectionValues()->get($someClass->getId())) { 

    $entity->addMyCollectionValue($someClass); 

} 

그러나 물론 올바르지 않습니다. 중복 키를 피하는 방법은?

답변

23

당신은 할 수 :

$object = $this->getDoctrine()->getRepository('MyBundle:MyClass')->find($id); 

if (!$entity->getMyCollectionValues()->contains($object)) { 
    $entity->addMyCollectionValue($object); 
} 

당신은 http://www.doctrine-project.org/api/common/2.1/class-Doctrine.Common.Collections.ArrayCollection.html

+0

오에 교리의 ArrayCollection의 사용 가능한 기능을 볼 수 있었다, 감사합니다! 잘 작동합니다! – spiil

+2

우리가 이미 그 객체의 id를 가지고있을 때, 우리가 찾고있는 객체를 가져 오기 위해 처음에 다른 질의를 실행하지 않고 Doctrine 방법을 검사합니까? 그 ID를 가진 항목이있는 컬렉션을 요청할 수없는 이유는 무엇입니까? 나는 그것에 대한 다른 쿼리를 추가해도 괜찮지 않다. – grantwparks

+1

@grantwparks 추가하기 전에 검사가 항상 이루어 지도록하려면 add 메서드 내에 contains()를 배치 할 수 있습니다. – TheGremlyn

관련 문제