【问题标题】:How to filter custom property on api-platform entity如何过滤 api 平台实体上的自定义属性
【发布时间】:2020-01-15 15:50:09
【问题描述】:

我在 Api Platform 中有一个实体,例如团队:

<?php

namespace App\Entity;


/**
 * @ORM\Entity(repositoryClass="App\Repository\Basketball\TeamRepository")
 * @ApiResource(
 *   routePrefix="/v2",
 *   normalizationContext={"groups"={"public:read"}, "enable_max_depth"=true},
 *   iri="http://schema.org/Team",
 *   collectionOperations={
 *     "get",
 *   },
 *   itemOperations={
 *     "get",
 *   },
 * )
 */
class Team implements ObjectManagerAware
{
  use \App\Entity\Traits\UUIDTrait;


  /**
   * @ORM\ManyToMany(targetEntity="App\Entity\Basketball\Event", mappedBy="teams")
   */
  private $events;


  public function __construct()
  {
    $this->events = new ArrayCollection();
  }


  /**
   * @return Collection|Event[]
   */
  public function getEvents(): Collection
  {
    return $this->events;
  }

  public function addEvent(Event $event): self
  {
    if (!$this->events->contains($event)) {
      $this->events[] = $event;
      $event->addTeam($this);
    }

    return $this;
  }

  public function removeEvent(Event $event): self
  {
    if ($this->events->contains($event)) {
      $this->events->removeElement($event);
      $event->removeTeam($this);
    }

    return $this;
  }

}

这一切正常,我可以加载团队和事件。我想做的是在 API 结果上有一个属性,它只返回即将发生的事件(而不是过去的事件)。这样做的“正确”方法是什么?我尝试添加自定义方法,例如

  /**
   * @return Collection|Event
   * @Groups({"public:read"})
   */
  public function getRemainingEvents(): ?Collection
  {
    $qb = $this->em->createQueryBuilder();
    $qb->select('e')->from(Event::class, 'e');
    $qb->where(
      $qb->expr()->orX($qb->expr()->eq('IDENTITY(e.home)', $this->getId()), $qb->expr()->eq('IDENTITY(e.away)', $this->getId()))
    );
    $qb->andWhere('e.startDate >= :d');
    $qb->andWhere('e.startDate >= :d');
    $qb->setParameter('d', (new \DateTime())->format('Y-m-d'));
    $qb->orderBy('e.startDate', 'ASC');
    $query = $qb->getQuery();
    return new ArrayCollection($query->getResult());
  } 

它确实做了我想要的,但是使用application/vnd.api+json 的api 结果并没有像“事件”属性那样列出“关系”中的事件。我试过查看自定义过滤器 (https://api-platform.com/docs/core/filters/#creating-custom-filters),但不明白实体上的自定义方法如何工作。

我希望remainingEvents 的行为与events 相同,并在响应的“关系”中列出相关项目。

有没有办法为序列化器注释它或使用过滤器?

【问题讨论】:

    标签: symfony doctrine-orm openapi api-platform.com


    【解决方案1】:

    我认为您意识到使用这种方法(实体中的一种方法从数据库中检索数据)是错误的。实体应该是虚拟的。

    关于你想要做什么,我认为你最好的解决方案应该是在“事件”资源中添加一个 DateFilter (https://api-platform.com/docs/core/filters/#date-filter),让你做一个GET events?startDate[after]=2019-09-18

    如果您想过滤来自特定“团队”资源的事件,只需向事件资源添加另一个过滤器,即搜索过滤器 (https://api-platform.com/docs/core/filters/#search-filter) 以指定团队,您可以执行以下操作: GET events?startDate[after]=2019-09-18&amp;team=IRIofteam_OR_ID

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-19
      相关资源
      最近更新 更多