完整性约束违规:1048列' user_id'不能为空

时间:2016-07-05 11:47:16

标签: php doctrine-orm doctrine symfony

当我想用setUserId()方法设置user_id时,我不知道为什么会出现此错误。

我在User类和Document类之间有一个ManyToOne关系。这样一个用户就可以拥有更多文档。是因为关系?

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;
}

这里我保存了我需要的东西:

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);
}

我收到了这个错误:

  

执行' INSERT INTO文件时发生异常(标题,   document,user_id)VALUES(?,?,?)'用params [" oim",null,null]:

     

SQLSTATE [23000]:完整性约束违规:1048列' user_id'   不能为空

..所以我的文档可以为null但user_id不是。任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:4)

尝试简单:

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

而不是:

$document->setUserId($id);

Doctrine知道如何管理关系以及如何填充正确的用户ID,因此方法setUserId不是必需的。

希望这个帮助

答案 1 :(得分:0)

我认为您应该将$id属性添加到用户实体并执行smth。像:

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

//some checking for existing user id
$user = new User();
$user->setId($this->getUser()->getId());
$repository = $this->getDoctrine()->getRepository('AppBundle:Document');
$document = new Document();


$document->setTitle($json->title);
$document->setUsers($user);

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

return new JsonResponse($json);
}

再一次:你需要调试$this->getUser()->getId()而不是数据库或实体,imho