- Published on
Api platform 教程8---Collection Providers
原创文章,转载时需取得本人同意并注明来源
- Authors
-
-
- Name
- langziyang
-
Api platform 教程8---Collection Providers
前一节我们讲解了item provider修改和添加数据,当然,如果同时存在provider和normalizer的话,你可以只需要normalizer来修改数据 。
接下来你可能会提出新的问题:对于这个collection提供的数据,如果我想完全自定义,即:数据是我通过原生sql语句查询到的呢?毕竟有一些场景 的查询逻辑实在奇葩到只能自己提供
if ($operation instanceof CollectionOperationInterface) {
$data = [];//比如说这里的data是通过原生sql取得
$count = 10;//这里的总条数也是通过sql的count取得
$paginator = $this->collectionProvider->provide($operation, $uriVariables, $context);
return new TraversablePaginator(
new \ArrayIterator($data),
$paginator->getCurrentPage(),//这里也可以通过$context['filters']['page']取得当前页
$paginator->getItemsPerPage(),//这里也可以通过$context['filters']['itemsPerPage']取得每页多少条
$count
);
}
我们对UserProvider文件中的逻辑进行了一次修改。现在提供的数据就完全是自己提供的了,对于分页和每页多少条,你需要确保在全局或者Entity中开启
api_platform:
defaults:
pagination_enabled: true
pagination_client_items_per_page: true
接下来我们给之前添加的宝藏指定用户或者新添加一个宝藏
{
"user": "/api/users/3"
}
当你的Entity中有关系表时,你需要使用@id提供对应数据。返回的数据可能如下:
{
"@context": "/api/contexts/DragonTreasure",
"@id": "/api/dragon_treasures/1",
"@type": "DragonTreasure",
"id": 1,
"name": "treasure 1",
"description": "treasure 1",
"value": 10,
"coolFactor": 5,
"createdAt": "2024-05-30T02:11:53+00:00",
"user": "/api/users/3",
"published": true
}
恭喜你,一点问题都没有,除了user字段和createdAt字段。这两个字段有什么问题呢?目前看来是一点问题都没有的。 但是你如果同时还是一个前端人员,你是否想在页面展示这个宝藏的时候还把user的名称显示出来?createdAt只显示年月日? 下一节我们讲解分组的使用