微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Symfony Api 平台过滤空值

如何解决Symfony Api 平台过滤空值

我的实体和表格如下。如您所见,我在表中有具有 ManyToOne 关系的父列。 子行使用父列过滤。我想获取父行或空父值。如何在 Symfony APi 平台中执行此操作?

我尝试过使用自定义查询扩展。但它适用于任何情况下的 where 条件。

# Table uyap_type
+-----------+--------------+------+-----+---------+----------------+
| Field     | Type         | Null | Key | Default | Extra          |
+-----------+--------------+------+-----+---------+----------------+
| id        | int(11)      | NO   | PRI | NULL    | auto_increment |
| parent_id | int(11)      | YES  | MUL | NULL    |                |
| code      | varchar(255) | NO   |     | NULL    |                |
| title     | varchar(255) | NO   |     | NULL    |                |
+-----------+--------------+------+-----+---------+----------------+
<?PHP

namespace App\Entity;

use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\NumericFilter;
use ApiPlatform\Core\Annotation\ApiFilter;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Repository\UyapTypeRepository;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ApiResource(
 *     collectionoperations={"get","post"},*     itemOperations={"get","put","delete"}
 * )
 * @ApiFilter(NumericFilter::class,properties={"parent.id"})
 * @ORM\Entity(repositoryClass=UyapTypeRepository::class)
 */
class UyapType
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string",length=255)
     */
    private $code;

    /**
     * @ORM\Column(type="string",length=255)
     */
    private $title;

    /**
     * @ORM\ManyToOne(targetEntity=UyapType::class)
     */
    private $parent;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getCode(): ?string
    {
        return $this->code;
    }

    public function setCode(string $code): self
    {
        $this->code = $code;

        return $this;
    }

    public function getTitle(): ?string
    {
        return $this->title;
    }

    public function setTitle(string $title): self
    {
        $this->title = $title;

        return $this;
    }

    public function getParent(): ?self
    {
        return $this->parent;
    }

    public function setParent(?self $parent): self
    {
        $this->parent = $parent;

        return $this;
    }
}

解决方法

$repository->findBy(
    ['parent' => null]
);

如果要添加带有控制器的路由,可以配置 itemOperations

https://api-platform.com/docs/core/controllers/#using-serialization-groups

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。