symfony4 - 如何通过 ID 更改 ManyToMany 的路径
问题描述
我使用 API-Platform 创建了一个 Symfony 项目,我想更改 Api 平台的默认行为,以实现多对多关系。默认情况下,这个返回关系路径,我希望他返回他的 ID
我阅读了 API-Platform 文档,但没有找到任何东西
use ApiPlatform\Core\Annotation\ApiResource;
/**
* @ApiResource(attributes={
* "normalization_context"={"groups"={"read"}}
* })
*/
class Work
{
/**
* @ORM\Column(type="string", length=255)
* @Groups("read")
*/
private $title;
/**
* @ORM\ManyToMany(targetEntity="App\Entity\WorkFilter", inversedBy="works")
* @Groups("read")
*/
private $filters;
}
我现在的 Json
[
{
"title": "Work 1",
"filters": [
"/api/work_filters/1",
"/api/work_filters/2"
]
}
]
所需的 Json
[
{
"title": "Work 1",
"filters": [
"1",
"2"
]
}
]
对不起我的英语不好
解决方案
最后我找到了解决方案
需要@groups
用于选择特定字段
use ApiPlatform\Core\Annotation\ApiResource;
/**
* @ApiResource(attributes={
* "normalization_context"={"groups"={"work"}}
* })
*/
class Work
{
/**
* @ORM\Column(type="string", length=255)
* @Groups("work")
*/
private $title;
/**
* @ORM\ManyToMany(targetEntity="App\Entity\WorkFilter", inversedBy="works")
* @Groups("work")
*/
private $filters;
}
use ApiPlatform\Core\Annotation\ApiResource;
/**
* @ApiResource(attributes={
* "normalization_context"={"groups"={"work"}}
* })
*/
class WorkFilter
{
/**
* @ORM\Column(type="string", length=255)
* @Groups("work")
*/
private $id;
}
[
{
"title": "Work 1",
"filters": [
{
"id": 1
},
{
"id": 2
}
]
}
]
推荐阅读
- algorithm - 比例分配算法
- python-3.x - Python列表理解字典和OpenCV
- javascript - 单独编译 Angular 组件并在 HTML 页面中一起使用它们
- maven - nexus-staging-maven-plugin 在没有信息的情况下返回 401
- reactjs - React Native - 未定义不是一个对象(评估'singleValue.stopTracking')
- ruby-on-rails - Rails 建模与多个用户的聊天室和对话的 ActiveRecord 关联
- sql - SQL:在记录插入时自动生成通用 ID
- powershell - 通过 PowerShell 发送电子邮件
- android - 如何找到我的应用在没有 Android Studio 的情况下停止的原因
- c# - 多线程 Aforge directshow 显示相机流和识别情绪