传递给App \ Entity \ CatalogComment :: setUserId()的参数1必须是App \ Entity \ User的实例或null,int给出

问题描述 投票:0回答:1

我正在尝试在我的关系ManyToOne中保存我的ID,但是返回了一个错误:

这就是我试图保存数据的方式:

    $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相关的我的Entity CatalogComment

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给出

我做错了什么?

谢谢你的时间。

symfony doctrine symfony4
1个回答
1
投票

我认为你必须调整实体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();

希望能帮助到你 :)

© www.soinside.com 2019 - 2024. All rights reserved.