我有用户实体,该实体具有与一个引用一样多的国家/地区字段:
/**
* @ORMManyToOne(targetEntity="Country")
*/
private $country;
/**
* Set country
*
* @param string $country
* @return User
*/
public function setCountry($country)
{
$this->country = $country;
return $this;
}
/**
* Get country
*
* @return string
*/
public function getCountry()
{
return $this->country;
}
我需要将当前用户表示为数组,因此在控制器中,我将当前用户表示为$user = $this->getUser();
并使用 JMSSerializer 和 json_decode 将对象转换为数组:
$userJSON = $serializer->serialize($user, 'json');
$user = json_decode($userJSON, true);
现在我将用户对象作为数组,但不是将国家/地区作为 ID,而是获得整个国家/地区对象。在用户对象中获取国家/地区作为 ID 的正确方法是什么?
为此,您必须使用 getter 注释:
/** @Accessor(getter="getCountryName") */
private $country;
public function getCountryName()
{
return $this->country->getName(); // or which property for country entity is used to take its name
}
并且不要忘记添加正在使用的JMS注释:
use JMSSerializerAnnotationAccessor;
祝你好运。