我的Symfony2项目中有一个名为Department的实体,它与一个实体用户具有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但是,如果我尝试使用数组集合,这将不起作用。
发布于 2017-02-03 23:33:41
这个解决方案可以为你工作
<?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;
}
}https://stackoverflow.com/questions/34818204
复制相似问题