我有一个父类MapItem和一个子类MapExhibit。我的MapExhibit类有一个属性$ builiding,它将展览绑定到特定的MapBuilding实体。当API调用JSON时,$ building应该不会出现在MapExhibit实体中。
注意我正在使用willdurand/Hateoas捆绑包
这是我目前的设置:
/**
* @ORM\Entity(repositoryClass="App\Repository\Map\MapItemRepository")
* @ORM\InheritanceType("JOINED")
* @ORM\DiscriminatorColumn(name="discr", type="string")
* @ORM\DiscriminatorMap({"item" = "MapItem", "bathroom" = "MapBathroom", "building" = "MapBuilding", "bus" = "MapBus", "emergency" = "MapEmergency", "exhibit" = "MapExhibit", "parking" = "MapParking"})
* @Serializer\XmlRoot("mapItem")
* @Hateoas\Relation("self", href = "expr('/api/mapitems/' ~ object.getId())")
*/
abstract class MapItem
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
* @Serializer\XmlAttribute
*/
private $id;
...
}
/**
* @ORM\Entity(repositoryClass="App\Repository\Map\MapExhibitRepository")
*
* @Hateoas\Relation(
* "building",
* exclusion = @Hateoas\Exclusion()
* )
*/
class MapExhibit extends MapItem
{
...
/**
* Many emergency devices can belong to one building.
* @ORM\ManyToOne(targetEntity="MapBuilding", inversedBy="emergencyDevices")
* @ORM\JoinColumn(name="building_id", referencedColumnName="id", nullable=true, onDelete="SET NULL")
*/
private $building;
...
public function getBuilding(): ?MapBuilding
{
return $this->building;
}
}
结果是一个JSON对象,它包含来自父MapItem的关系
"_links":{"self":{"href":"\/api\/mapitems\/29"}}}]
但也包括展览大楼的数据。这一部分应该被忽略。
答案 0 :(得分:0)
Take a look on exclusion strategies in documentation.
If you would like to always expose, or exclude certain properties. Then, you can do this with the annotations @ExclusionPolicy, @Exclude, and @Expose.
The default exclusion policy is to exclude nothing. That is, all properties of the object will be serialized. If you only want to expose a few of the properties, then it is easier to change the exclusion policy, and only mark these few properties: (...)
So basically, put @Serializer\Exclude()
above private $builidng
. Don't forget to add use JMS\Serializer\Annotation as Serializer;
on top.