lorenos lorenos - 4 months ago 54
PHP Question

Integrity constraint violation: 1048 Column 'user_id' cannot be null

i don't know why I'm getting this error when I wanna set user_id with setUserId() method.

I have a ManyToOne relationship between User class and Document class. So that one user can have more documents. Is it because the relationship?

User.php

/**
* @ORM\OneToMany(targetEntity="Document", mappedBy="users")
*/
private $documents;


/**
* Add document
*
* @param \AppBundle\Entity\Document $document
*
* @return User
*/
public function addDocument(\AppBundle\Entity\Document $document)
{
$this->documents[] = $document;

return $this;
}


Document.php

/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="documents")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $users;

/**
* Set users
*
* @param \AppBundle\Entity\User $users
*
* @return Document
*/
public function setUsers(\AppBundle\Entity\User $users)
{
$this->users = $users;

return $this;
}

/**
* Set userId
*
* @param integer $userId
*
* @return Document
*/
public function setUserId($userId)
{
$this->user_id = $userId;

return $this;
}


Here im saving what i need:

public function createAction(Request $request)
{
$content = $request->getContent();
$json = json_decode($content);

$id = $this->getUser()->getId();
$repository = $this->getDoctrine()->getRepository('AppBundle:Document');
$document = new Document();
//$user_id = $id;

$document->setTitle($json->title);
$document->setUserId($id);

$em = $this->getDoctrine()->getManager();
$em->persist($document);
$em->flush();

return new JsonResponse($json);
}


And im getting this error:

An exception occurred while executing 'INSERT INTO document (title, document, user_id) VALUES (?, ?, ?)' with params ["oim", null, null]:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null

..So my document can be null but user_id not. Can anyone help me?

Answer

Try simply:

$document->setUser($this->getUser());

instead of:

$document->setUserId($id);

Doctrine know how to manage the relation and how to populate the correct user id, so the method setUserId is not necessary.

Hope this help

Comments