如何在Shopware 6 Store API中一次性获取所有翻译内容?
一次性获取Shopware Store API分类的所有翻译内容
可以实现一次性获取所有分类的全部翻译实例,主要有两种可行方案:
方案1:使用Store API的关联参数直接加载翻译
Shopware 6的Store API支持通过associations参数加载关联数据,你可以在请求中指定加载分类的translations关联,从而一次性获取所有语言的翻译内容。
请求示例
GET /store-api/category?associations[translations]=*&limit=1000
参数说明
associations[translations]=*:指定加载分类的所有翻译关联数据,返回的每个分类对象中会包含translations数组,每个数组元素对应一种语言的翻译(包含languageId、name、description等字段)。limit=1000:设置足够大的限制值以获取所有分类(如果你的分类数量超过1000,可调整该值或结合分页参数page使用)。
返回结构示例
{ "data": [ { "id": "xxx", "name": "默认语言分类名称", "translations": [ { "languageId": "de-DE", "name": "德语分类名称", "description": "德语分类描述" }, { "languageId": "en-GB", "name": "English Category Name", "description": "English Category Description" } ] } ] }
方案2:自定义Store API路由扩展(进阶)
如果默认的关联加载无法满足你的需求(比如需要强制忽略当前语言上下文、添加额外过滤逻辑),可以通过自定义插件扩展默认的CategoryRoute来实现。
步骤1:创建扩展路由类
<?php namespace YourPlugin\Core\Content\Category\Api; use Shopware\Core\Content\Category\Api\CategoryRoute; use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria; class ExtendedCategoryRoute extends CategoryRoute { protected function prepareCriteria(Criteria $criteria): void { parent::prepareCriteria($criteria); // 强制加载所有翻译关联,不受当前请求语言限制 $criteria->addAssociation('translations'); // 可根据需求添加额外的过滤、排序逻辑 // $criteria->addFilter(...); } }
步骤2:注册路由装饰器
在插件的src/Resources/config/services.xml中配置服务,覆盖默认的分类路由:
<service id="YourPlugin\Core\Content\Category\Api\ExtendedCategoryRoute" decorates="Shopware\Core\Content\Category\Api\CategoryRoute"> <argument type="service" id="YourPlugin\Core\Content\Category\Api\ExtendedCategoryRoute.inner"/> <argument type="service" id="Shopware\Core\Content\Category\CategoryRepository"/> <argument type="service" id="Shopware\Core\Framework\DataAbstractionLayer\Search\CriteriaValidator"/> <argument type="service" id="Shopware\Core\Framework\DataAbstractionLayer\Search\Sorting\SortingParser"/> <argument type="service" id="Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\FilterParser"/> <argument type="service" id="Shopware\Core\Framework\DataAbstractionLayer\Search\Aggregation\AggregationParser"/> <argument type="service" id="Shopware\Core\Framework\DataAbstractionLayer\Search\Query\QueryParser"/> <argument type="service" id="Shopware\Core\Framework\DataAbstractionLayer\Search\SearchContextFactory"/> </service>
步骤3:安装并激活插件
完成代码编写后,安装并激活自定义插件,之后请求原/store-api/category端点时,就会自动返回所有分类的多语言翻译内容。
内容的提问来源于stack exchange,提问作者Ali
相关产品推荐
相关产品推荐

