如何从Symfony3的Doctrine实体中获取所有值?附代码示例
看起来你现在的问题是没法从ChangeLog实体中获取所有属性值,核心原因出在JMS序列化的配置和实体的访问方法上,我给你一步步拆解解决方案:
先明确问题根源
你的Entity.ChangeLog.yml里设置了exclusion_policy: ALL,这意味着所有属性默认都不会被序列化输出,只有显式标记expose: true的字段才会被返回。目前你只给date开了暴露,所以返回结果里自然只有date的值。
解决方案1:显式暴露所有需要的属性
更新你的序列化配置,把要获取的属性都加上expose: true,同时处理好关联实体的序列化逻辑:
AppBundle\Entity\ChangeLog: exclusion_policy: ALL properties: id: type: integer expose: true # 新增:暴露id字段 access_type: public_method # 要求实体必须有getId()方法 date: access_type: public_method expose: true type: datetime user: type: AppBundle\Entity\Category access_type: public_method expose: true # 新增:暴露关联的user字段 depth: 1 # 可选:限制关联层级,避免循环引用(比如Category又关联了ChangeLog)
解决方案2:全局取消排除策略(不推荐,除非确实需要所有属性)
如果要返回实体的全部属性,可以把排除策略改成NONE,这样默认所有属性都会被序列化,不用逐个标记:
AppBundle\Entity\ChangeLog: exclusion_policy: NONE properties: # 只对特殊属性做额外配置即可,比如日期格式 date: type: datetime format: 'Y-m-d H:i:s' # 自定义返回的日期格式 user: depth: 1 # 防止关联实体的循环引用问题
关键前提:确保实体有正确的Getter方法
因为你的配置里用了access_type: public_method,所以ChangeLog实体必须为每个属性提供对应的getter方法,比如:
// src/AppBundle/Entity/ChangeLog.php namespace AppBundle\Entity; use DateTime; use AppBundle\Entity\Category; class ChangeLog { private $id; private $date; private $user; // ID的Getter public function getId(): ?int { return $this->id; } // 日期的Getter public function getDate(): ?DateTime { return $this->date; } // 用户关联的Getter public function getUser(): ?Category { return $this->user; } // ... 其他Setter方法(如果业务需要) }
控制器代码优化(可选)
你的现有控制器有个小问题:findAll()永远返回数组(空数组或实体数组),不会返回null,所以可以调整得更严谨:
public function getLogAction() { $changeLogs = $this->getDoctrine() ->getRepository(ChangeLog::class) ->findAll(); if (empty($changeLogs)) { return new View("Log not found", Response::HTTP_NOT_FOUND); } return new View($changeLogs, Response::HTTP_OK); }
关联实体序列化注意事项
如果user关联的Category实体也需要序列化输出,要给它也配置对应的序列化规则,同样注意避免循环引用(比如Category里如果有指向ChangeLog的关联,一定要用depth或者序列化组控制层级)。
内容的提问来源于stack exchange,提问作者Dialkord
相关产品推荐
相关产品推荐

