搜索记录数组


search through array of records

我在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.');
  }
    ////.....

}

所有这些都很简单,但我真的不知道如何浏览属于$category的部分。为了进行编辑,我需要一个特定的记录,它的id==$id。显然,我不能简单地浏览所有的部分,因为那样我就不知道我找到的是否真的属于$category。有什么简单的方法可以让我做到这一点,或者我应该一个接一个地简单循环这个$category->getSections()吗?

解决方案非常简单。

您可以依靠ParamConverter来加载必要的对象如果没有找到任何一个,它将失败

您可以在此处阅读有关它的更多信息。不要忘记导入(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
    ...
}