2016-01-15 31 views
2

我在Symfony2项目中有一个实体,名为Department,它与实体User具有OneToMany关系。我试图通过Bazinga Hateoas包来嵌入用户数组集合。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

关于这方面的消息工作?你知道了吗? – DonCallisto

回答

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; 
    } 
}