传递给 App\Entity\CatalogComment::setUserId() 的参数 1 必须是 App\Entity\User 的实例或 null,给定的 int
Argument 1 passed to App\Entity\CatalogComment::setUserId() must be an instance of App\Entity\User or null, int given
我正在尝试将我的 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 given
我做错了什么?
感谢您的宝贵时间。
我认为您必须调整 Entity CatalogComment 中的映射关系,不要使用 属性 $userId,而是使用类型为 User
的 属性 $user
class CatalogComment
{
// ...
/**
* @ManyToOne(targetEntity="User")
* @JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
}
您还必须为 $user 创建 getter 和 setter,然后您可以在 CatalogComment 对象中设置用户,如下所示
$user = $this->getUser();
$catalogComment = new CatalogComment();
$catalogComment->setUser($user);
$em = $this->getDoctrine()->getManager();
$em->persist($catalogComment);
$em->flush();
希望对您有所帮助:)
我正在尝试将我的 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 given
我做错了什么?
感谢您的宝贵时间。
我认为您必须调整 Entity CatalogComment 中的映射关系,不要使用 属性 $userId,而是使用类型为 User
的 属性 $userclass CatalogComment
{
// ...
/**
* @ManyToOne(targetEntity="User")
* @JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
}
您还必须为 $user 创建 getter 和 setter,然后您可以在 CatalogComment 对象中设置用户,如下所示
$user = $this->getUser();
$catalogComment = new CatalogComment();
$catalogComment->setUser($user);
$em = $this->getDoctrine()->getManager();
$em->persist($catalogComment);
$em->flush();
希望对您有所帮助:)