首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Bazinga Hateoas:嵌入数组集合

Bazinga Hateoas:嵌入数组集合
EN

Stack Overflow用户
提问于 2016-01-16 03:17:17
回答 1查看 465关注 0票数 2

我的Symfony2项目中有一个名为Department的实体,它与一个实体用户具有OneToMany关系。我正在尝试通过Bazinga Hateoas包嵌入一个用户数组集合。

如果我嵌入一个用户,一切都会正常工作。在这个例子中,我嵌入了一个实体的单个实例。

代码语言:javascript
复制
  @Hateoas\Relation(
    "user",
    href = "expr('/api/staff/' ~ object.getUser().getId())",
    embedded = "expr(object.getUser())",
    exclusion = @Hateoas\Exclusion(excludeIf = "expr(object.getUser() === null)")
  )  //works

但是,如果我尝试使用数组集合,这将不起作用。

EN

回答 1

Stack Overflow用户

发布于 2017-02-03 23:33:41

这个解决方案可以为你工作

代码语言:javascript
复制
<?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;
    }   
 }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34818204

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档