0
我有2個實體 - 用戶和項目。它們之間的關係是這樣的:在Symfony2中的關係之間設置方法
// Acme/MyBundle/Entity/Project.php
...
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="projects")
* @ORM\JoinColumn(name="author_id", referencedColumnName="id")
*/
private $author;
public function setAuthor(\Acme\MyBundle\Entity\User $author = null)
{
$this->author = $author;
return $this;
}
... other set/get methods...
和
// Acme/MyBundle/Entity/User.php
...
/**
* @ORM\OneToMany(targetEntity="Project", mappedBy="author")
*/
private $projects;
public function addProject(\Acme\MyBundle\Entity\Project $projects)
{
$this->projects[] = $projects;
return $this;
}
... other set/get methods...
當我試圖創建一個項目,並指定當前用戶爲作者(以及用戶的字段中添加項目,會出現問題)。
這是我在項目控制器createAction:
public function createAction(Request $request, $user_id)
{
$entity = new Project();
// THE PROBLEM PART
$entity->setAuthor($user_id);
$user = getUser($user_id); // get the user and attach the project
$user->addProject($entity->getId());
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect('homepage');
}
return $this->render('AcmeMyBundle:Project:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
而且很明顯它返回我一個錯誤,指出「傳遞給...參數1必須的情況下......」。
任何想法如何解決它?
p.s.這是我第一次嘗試學習symfony2
哈,我已經試過幾乎所有的東西,除了這個,謝謝@urbani :) – nevermind