【问题标题】:Argument 1 passed to App\Entity\CatalogComment::setUserId() must be an instance of App\Entity\User or null, int given传递给 App\Entity\CatalogComment::setUserId() 的参数 1 必须是 App\Entity\User 的实例或 null,int 给定
【发布时间】: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
  • 很高兴你能成功。考虑接受下面的答案,因为这个人确实花时间写它。

标签: symfony doctrine symfony4


【解决方案1】:

我认为您必须调整实体目录注释中的映射关系,使其不具有属性 $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();

希望对你有帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    相关资源
    最近更新 更多