2017-10-09 23 views
0

有一種方法來連接symfony中的findBy操作的兩個結果?如果產品是由用戶創建的,我試圖將用戶對象連接到產品陣列。我的代碼:從getRepository連接結果symfony

public function indexAction() 
{ 
    $products = $this->getDoctrine() 
     ->getRepository('AppBundle:Product') 
     ->findById($this->getUser()->getId()); 

    if ($products[0]->getCreatedByUser() == 1){ 
     $userDetails = $this->getDoctrine()->getRepository('AppBundle:User') 
     ->findOneById($product->getUserId()); 

    //here somehow to concatenate the value from $user to the $products array 
    } 

    return $this->json($products, Response::HTTP_OK, [], [ 
     'groups' => ['products'] 
    ]); 
} 
+0

添加樣本輸入和輸出。 – svgrafov

+0

我不認爲' - > findOneById($ id)'(除非您以不同的方式實現它,它與' - > find($ id)''相同)做你認爲它的作用。 – ccKep

+0

不,不是...... – IleNea

回答

0

您可以創建一個對象,該對象持有指向$ user和$ products數組的值的指針。或者,您可以使用(value,key)創建一個數組來映射依賴關係。

但是,你爲什麼要在控制器級別上做到這一點?

創建數據庫(onetoOne)關係不是更好嗎?通過這種方式,您可以查詢產品,並且它也會加載userDetails。然後,您可以在twigview中訪問您的userDetails,例如:{{ products.product.userDetails.username }},而無需在您的控制器中使用任何業務邏輯。