2013-06-07 3 views
0

컨트롤러에서 getName()에 액세스하려고하는데 작동하지 않습니다.symfony getName()이 컨트롤러 내부에서 작동하지 않습니다.

하지 않는 일 :

$supplier = $em->getRepository('WICSupplierBundle:Supplier')->findBy(array('account'=>$account_id, 'id'=>$id)); 
$supplierName = $supplier->getName(); 
This doesnt return the name from the db.... 
I get the error: "Error: Call to a member function getName() on a non-object..." 

작동합니까 :

$supplier = $em->getRepository('WICSupplierBundle:Supplier')->find($id); 
$supplierName = $supplier->getName(); 
This returns the name from the db.... 

왜?

+0

은 - VAR 타입 오브젝트되지 배열 리턴? var_dump를 시도 하시겠습니까? – sinisake

답변

-2

나는 주위를 둘러 보았다 , 내가) (

$supplier = $em->getRepository('WICSupplierBundle:Supplier') 
->findBy(
array('account'=>$account_id), ## array 1 
array('id'=>$id)    ## array 2 
); 

$ supplierName = $ supplier-> getName, 여러 배열을 사용 할 필요가 있다고 생각;
업데이트 : 다시 documentation을 다시 읽은 후 두 번째 배열은 정렬 용으로 나타납니다.

0

Jessica의 대답을 확장하면 findBy() 저장소 메서드는 Supplier 엔터티의 인스턴스 인 개체 배열을 반환하지만 find()은 단일 엔터티를 반환합니다. 만약 당신이 하나만을 원한다면, 첫 번째 메소드에서 getName 메소드를 호출하면된다.

$suppliers = $em->getRepository('WICSupplierBundle:Supplier') 
    ->findBy(array(
     'account' => $account_id, 
     'id'  => $id 
    )); 

if (count($suppliers) < 1) { 
    // Assuming the code is in a controller 
    throw $this->createNotFoundException('No such supplier found.'); 
} 

$supplierName = $suppliers[0]->getName(); 

또는 더 나은 아직,

$supplier = $em->getRepository('WICSupplierBundle:Supplier') 
    ->findOneBy(array(
     'account' => $account_id, 
     'id'  => $id 
    )); 

if (!$supplier) { 
    throw $this->createNotFoundException('No such supplier found.'); 
} 

$supplierName = $supplier->getName(); 
1

"findBy"이 때문에 findOneBy() 콜렉션/배열을 반환합니다. 당신의 작업 예제에서 (찾기); ID 필드를 참조하는 정확한 "하나"결과 만 찾고 정의 된 변수에서 getters (getName())를 직접 호출 할 수 있습니다.

또는 findOneBy를 사용하여 다른 조건으로 하나의 결과를 볼 수 있습니다.

다른 공급 업체 이름을 얻으려면 foreach 함수를 사용하여 각 엔티티에 도달해야합니다. 예를 들어

: 함께

$supplier = $em->getRepository('WICSupplierBundle:Supplier')->findBy(array('account'=>$account_id, 'id'=>$id)); 
$supplierName = $supplier->getName(); 

:

foreach($supplier as $s) 
{ 
    echo $s->getName(); 
} 
0

이 장착 제 경우

$supplier = $em->getRepository('WICSupplierBundle:Supplier')->findOneBy(array('account'=>$account_id, 'id'=>$id)); 
$supplierName = $supplier->getName();