问题描述
我的实体和表格如下。如您所见,我在表中有具有 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