首页 > 解决方案 > 尽管为实体正确设置了值,但为什么我会出错?

问题描述

您好,我的网站是由 symfony 和 mysql 制作的。现在我陷入了这个错误。

publisher_id 不能为空。

这个错误意味着publisher_id卷表的列不能为空。这个错误是正确的,但我将值设置为publisher_id 并且我确实var_dump喜欢下面并且我得到了正确的实体。

$volume = new Volume(); //instanciate Volume Entity.
$volume->setISBN($ISBN);
$volume->setStorePublisher($publisher); //set Publisher Entity to Volume Entity.

var_dump($publisher->getId()); //correct id shown.why no publisher id???

$volume->setCreatedAt(Context::now());
$volume->setUpdatedAt(Context::now());

$em = Context::getEntityManagerWrite();
$em->transactional(function (EntityManager $em) use (&$volume) {
    $volume = $em->merge($volume); // i got error here.why ??
    $em->flush();
    //....
}

标签: symfonydoctrine

解决方案


你的错误:

从您尝试合并非托管实体的问题开始,将其保留在em第一个实体中:

$volume = new Volume();
$volume->setISBN($ISBN);
$volume->setStorePublisher($publisher); 
$volume->setCreatedAt(Context::now());
$volume->setUpdatedAt(Context::now());

$em->persist($volume);

// do stuff

供参考:

在您的实体中添加从控制器__construct中删除此丑陋的方法createAt()

class Volume {

    public function __construct()
    {
        $this->setCreateAt(new \DateTime());
    }
}

对于您可以使用DocupdateAt()中所示的服务。目标是让您尽可能轻松。Controller


推荐阅读