使用API​​平台规范化虚拟属性

时间:2020-02-03 15:35:36

标签: php symfony serialization symfony4 api-platform.com

我正在尝试使用API​​平台返回虚拟属性,但是我唯一能得到的就是IRI。

我有多个用户,链接到多个组织。这些组织只有一个“所有者”(用户类)。

我想要一个名为“ coach”的属性,该属性返回第一个组织的所有者

情况有些复杂,但我简化了。

App \ Entity \ User

/**
 * @ApiResource(
 *      itemOperations={
 *          "get"={"security"="is_granted('view', object)"},
 *      },
 *      normalizationContext={"groups"={"user", "user:read"}},
 *      denormalizationContext={"groups"={"user", "user:write"}}
 * )
 * @ORM\Table(name="user")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    protected $id;

    /**
     * @Groups({"user"})
     */
    protected $email;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     * @Groups({"user"})
     */
    private $firstName;

    /**
     * @ApiProperty()
     * @Groups({"user"})
     */
    private $coach;

    /**
     * User constructor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->organizations = new ArrayCollection();
    }

    [...]

    public function getCoach(): ?User
    {
        $coach = null;
        if (count($this->getOrganizations()) > 0) {
            $coach = $this->getOrganizations()->first()->getOwnerUser();
        }

        return $coach;
    }
}

我仍然得到

{
    email: xxx;
    firstName: xxx;
    organizations: [
       {
          name: xxx;
       },
       {
          name: xxx;
       }
    ],
    coach: "/api/users/4"
}

我想要一个合适的用户

{
    email: xxx;
    firstName: xxx;
    organizations: [
       {
          name: xxx;
       },
       {
          name: xxx;
       }
    ],
    coach: {
       email: xxx;
       firstName: xxx;
    }
 }

0 个答案:

没有答案