Symfony 3.4报错:EntityManager::$flush属性未定义及服务创建失败
解决Doctrine EntityManager的"Undefined property"错误
嘿,我一眼就看出问题出在哪了——你遇到的Undefined property: Doctrine\ORM\EntityManager::$flush错误,核心原因是你把Doctrine EntityManager的flush()方法当成属性来访问了。也就是说你大概率写了$em->flush(没有括号),但正确的写法是调用方法:$em->flush()。
看你提供的代码,应该是在创建Notification实体后,想要把它保存到数据库,但代码没写完就出问题了。我帮你把完整的修正版代码写出来:
class NotificationService { public $manager; public function __construct($manager) { $this->manager = $manager; } public function set($user, $type, $typeId, $extra = null){ $em = $this->manager; $notification = new Notification(); $notification->setUser($user); $notification->setType($type); $notification->setTypeId($typeId); $notification->setReaded(0); $notification->setCreatedAt(new \DateTime('now')); // 补上你没写完的设置extra的逻辑(假设你的实体有这个方法) if ($extra !== null) { $notification->setExtra($extra); } // 关键:先把实体交给EntityManager管理 $em->persist($notification); // 调用flush方法同步到数据库(必须带括号!) $em->flush(); } }
再给你划两个重点:
- Doctrine的
EntityManager里,flush()是一个方法,不是属性。直接写$em->flush会让PHP尝试访问一个不存在的属性,自然抛出错误。 - 保存实体的时候,要先调用
persist()把实体加入EntityManager的跟踪队列,再调用flush()把所有待处理的变更同步到数据库,缺一不可哦。
内容的提问来源于stack exchange,提问作者Chris Michel
相关产品推荐
相关产品推荐

