I'm trying to save my ID in my relation ManyToOne, but an error returned:
This is how i'm trying to save data:
$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');
}
And this is my Entity CatalogComment related with the relation user_id
public function getUserId(): ?User
{
return $this->user_id;
}
public function setUserId(?User $user_id): self
{
$this->user_id = $user_id;
return $this;
}
The error received is:
Argument 1 passed to App\Entity\CatalogComment::setUserId() must be an instance of App\Entity\User or null, int given
What i'm doing wrong?
Thanks for your time.
I think you have to adjust your mapped relationship in the Entity CatalogComment not to have a property $userId but instead a property $user which should be of type User
class CatalogComment
{
// ...
/**
* @ManyToOne(targetEntity="User")
* @JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
}
You have to create getter and setter for $user too, and then you can set the user in an CatalogComment Object as follows
$user = $this->getUser();
$catalogComment = new CatalogComment();
$catalogComment->setUser($user);
$em = $this->getDoctrine()->getManager();
$em->persist($catalogComment);
$em->flush();
Hope it helps :)