我有2个实体 - 用户和项目。它们之间的关系如下:
// 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...
当我尝试创建项目并将当前用户指定为作者(并在用户的字段中添加项目)时,会出现问题。
这是我在Project控制器中的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
答案 0 :(得分:1)
在这种情况下,你可以给Doctrine(Symfony的默认ORM)而不是它的id。 Doctrine会发现它只需要将id保存到数据库中。
所以它会是:
$user = $this->getUser($user_id);
$entity->setAuthor($user);
你也不需要在项目中设置它,这也是由Doctrine负责的。