You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:33:39