我有一个模型
/**
* @ORMTable(name="polygon")
* @ORMEntity(repositoryClass="MyBundleRepositoryPolygonRepository")
* @JMSExclusionPolicy("none")
*/
class Polygon {
/**
* @var string
*
* @ORMColumn(name="polygon", type="json_array")
* @JMSType("array<MyBundleModelPoint>")
*/
private $points;
/***/
}
DB存储像文本"[{"x":1、"y":1}…]"
在控制器中我有
/**
* Matches /polygon exactly
*
* @Route("/", name="polygon_list")
* @Method("GET")
*
* @RestGet("/")
*
*/
public function listAction()
{
return $this->container->get('doctrine.orm.entity_manager')
->getRepository('MyBundle:Polygon')
->findAll();
}
所以我得到ReflectionProperty::getValue()期望参数1为给定的对象数组
…供应商/jms/元数据/src/元数据/PropertyMetadata.php: 51
如果只得到结果,可以使用虚属性
来解决。/**
* @JMSExclude
*/
private $points;
/**
* @JMSVirtualProperty
* @JMSType("array<MyBundleModelPoint>")
* @JMSSerializedName("points")
* @JMSGroups({"common"})
*
* @return array
*/
public function getMyPoints() {
return [new Point(), new Point()]
}
但是我需要从POST接收这个点作为JSON,所以到目前为止我发现的唯一方法是类似的教条自定义类型https://github.com/sonata-project/sonata-doctrine-extensions
唯一不同的是,在convertToPHPValue方法中,我添加了额外的类型转换来接收对象,而不是关联数组:
// pass my [{"x":1, "y":1} ...]
public function convertToPHPValue($value, AbstractPlatform $platform)
{
return array_map(function($a){ return (object)$a;}, json_decode($value));
}
是否有一个更干净的解决方案,不添加自定义原则序列化?
if only this…供应商/jms/元数据/src/元数据/PropertyMetadata.php: 51有
return $this->reflection->getValue((object)$obj);
的
return $this->reflection->getValue($obj); // :(
我的问题是在使用@JMSType
class Polygon {
/**
* @ORMColumn(name="polygon", type="json_array")
*/
private $points;
public function getPoints() { return $this->points;}
public function setPoints($points) {
$this->points = $points;
return $this;
}
/***/
}
工作得很好,谢谢@Matteo指出我使事情复杂化了:)