【发布时间】:2019-03-11 18:31:01
【问题描述】:
我正在尝试将我的 ID 保存在我的关系 ManyToOne 中,但返回了一个错误:
这就是我尝试保存数据的方式:
$user = $this->getUser()->getId();
$catalogcomment = new CatalogComment();
$form = $this->createForm(CatalogCommentType::class, $catalogcomment);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$catalogcomment->setUserId($user);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($catalogcomment);
$entityManager->flush();
return $this->redirectToRoute('catalog_index');
}
这是我与关系 user_id 相关的实体目录评论
public function getUserId(): ?User
{
return $this->user_id;
}
public function setUserId(?User $user_id): self
{
$this->user_id = $user_id;
return $this;
}
收到的错误是:
传递给 App\Entity\CatalogComment::setUserId() 的参数 1 必须是 App\Entity\User 的实例或 null,int 给定
我做错了什么?
感谢您的宝贵时间。
【问题讨论】:
-
Doctrine ORM 可能有点难以适应,尤其是当人们来自更“sqlish”的背景时。在大多数情况下,您处理的是对象而不是对象 ID。所以使用: $user = $this->getUser();并将您的 CatalogComment 内容更改为 get/setUser 而不是 userId。更好的是,工作考虑了文档中的一些示例,只是为了了解事情是如何工作的。
-
你说得对,只是改了 $user = $this->getUser()->getUsername();对于 $user = $this->getUser();它就像一个魅力。 xD
-
很高兴你能成功。考虑接受下面的答案,因为这个人确实花时间写它。