2014-09-04 72 views
-1

我有Category和Sections之間的OneToMany關係。我想要做的是實現編輯部分。所以,我的編輯行動到目前爲止是這樣的:通過記錄數組搜索

/** 
    * 
    * 
    * @Route("category/{category_id}/section/{id}/edit", name="section_edit") 
    * @Method("GET") 
    * @Template() 
    */ 



public function editAction($category_id, $id) 

    { 
     $em = $this->getDoctrine()->getManager(); 

    $category = $em->getRepository('MyOwnBundle:Category')->find($category_id); 

    if (!$category) { 
     throw $this->createNotFoundException('Unable to find Category entity.'); 
    } 

    ////..... 

}

都相當簡單,但我真的不知道如何瀏覽屬於$類別部分。要執行編輯,我需要這個特定的記錄,其中有id == $ id。顯然,我不能簡單地通過所有的部分,因爲然後我wouldnt知道我是否真的屬於$類別。任何簡單的方法,將允許我這樣做,或者我應該簡單循環通過這個$category->getSections()一個接一個?

回答

0

該解決方案非常簡單。

您可以依靠ParamConverter加載necesarry對象。 如果找不到任何一個,它將會失敗

您可以閱讀更多關於它here。不要忘記導入(use)ParamConverter註釋!

/** 
* @Route("category/{category_id}/section/{id}/edit", name="section_edit") 
* @ParamConverter("category", class="AcmeBundle:Category", options={"id": "category_id"}) 
* @Method("GET") 
* @Template() 
*/ 
public function editAction(Category $category, Section $section){ 
    // both category and section are fully loaded, no need to go to doctrine or check if they are null 

    if (!$section->getCategories()->contains($category)){ 
     throw $this->createNotFoundException('Invalid request.'); 
    } 

    ... 
    the rest of your logic 
    ... 
}