简体   繁体   English

插入外键值

[英]Insert foreign key value

I have two entities Project and Task. 我有两个实体Project和Task。 Task`s project_id value is mapped with project`s id.Every time creating a new task for a specific project, the project_id in the Task table should be set. 任务的project_id值与项目id一起映射。每次为特定项目创建新任务时,应设置Task表中的project_id。 Is there another way of doing this except using the hidden input field form? 除了使用隐藏的输入字段表单之外,还有其他方法吗?

createAction of TaskController TaskController的createAction

  public function createAction(Request $request)
  {
    $entity = new Tasks();
    $form = $this->createCreateForm($entity);
    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($entity);
        $em->flush();

        return $this->redirect($this->generateUrl('tasks_show', array('id' => $entity->getId())));
    }

    return $this->render('TestBundle:Tasks:new.html.twig', array(
        'entity' => $entity,
        'form'   => $form->createView(),
    ));
}

是的,在处理表单的控制器操作中调用setProject($project)方法

First you need to get project that you want to assign tasks to it. 首先,您需要获得要为其分配任务的项目。 For example you can send it via Request $request then use it to query for Project Object then assign task to this object. 例如,您可以通过Request $request发送它,然后使用它查询Project Object然后将任务分配给该对象。

public function createAction(Request $request)
  {
    $entity = new Tasks();

    // doctrine entity manager
    $em = this->getDoctrine()->getManager();

    // get project_id from query string
    $project_id = $request->get('project_id');

    // query database for project object
    $project = $em->getRepository("TestBundle:Project")->find($project_id);

    // assign task to project object
    $entity->setProject($project);

    $form = $this->createCreateForm($entity);
    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($entity);
        $em->flush();

        return $this->redirect($this->generateUrl('tasks_show', array('id' => $entity->getId())));
    }

    return $this->render('TestBundle:Tasks:new.html.twig', array(
        'entity' => $entity,
        'form'   => $form->createView(),
    ));
}

Also newAction() is better place to do this. 同样, newAction()是执行此操作的更好的位置。

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM