我的Symfony2项目中有一个名为Department的实体,它与实体User具有OneToMany关系。我试图通过Bazinga Hateoas捆绑包嵌入一个用户数组。
如果我嵌入一个用户,一切正常。在这个例子中,我嵌入了一个实体的单个实例。
@Hateoas\Relation(
"user",
href = "expr('/api/staff/' ~ object.getUser().getId())",
embedded = "expr(object.getUser())",
exclusion = @Hateoas\Exclusion(excludeIf = "expr(object.getUser() === null)")
) //works
但是,如果我尝试使用数组集合,这不起作用。
答案 0 :(得分:0)
此解决方案可以为您服务
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as JMS;
use Hateoas\Configuration\Annotation as Hateoas;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @JMS\ExclusionPolicy("all")
* @Hateoas\Relation(
* "self",
* href = @Hateoas\Route(
* "get_department",
* parameters = { "id" = "expr(object.getId())" }
* )
* )
* @Hateoas\Relation(
* "users",
* href = @Hateoas\Route(
* "get_user",
* parameters = { "id" = "expr(object.getId())" }
* ),
* embedded = @Hateoas\Embedded(
* "expr(object.getUsers())",
* exclusion = @Hateoas\Exclusion(
* excludeIf = "expr(object.getUsers().isEmpty() === true)",
* groups={"users"},
* maxDepth = 1
* )
* ),
* exclusion = @Hateoas\Exclusion(
* excludeIf = "expr(object.getUsers().isEmpty() === true)",
* groups={"users"},
* maxDepth = 1
* )
* )
*/
class Department
{
/**
* @var ArrayCollection
*
* @ORM\OneToMany(targetEntity="AppBundle\Entity\User", mappedBy="department")
* @JMS\MaxDepth(1)
*/
protected $users;
/**
* Add user
*
* @param \AppBundle\Entity\User $user
*
* @return Department
*/
public function addUser(\AppBundle\Entity\User $user)
{
$this->users[] = $user;
return $this;
}
/**
* Remove user
*
* @param \AppBundle\Entity\User $user
*/
public function removeUser(\AppBundle\Entity\User $user)
{
$this->users->removeElement($user);
}
/**
* Get users
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getUsers()
{
return $this->users;
}
}