首页 > 解决方案 > 如何扩展 shopware.api.customergroup

问题描述

我正在尝试通过向其添加属性来扩展 Shopware v5.4.6 的 \Shopware\Components\Api\Resource\CustomerGroup 但它没有显示在 API 响应中。

我试图重新调整扩展客户 API 资源示例的用途,但它不起作用。

“SwagExtendCustomerGroupResource\Components\Api\Resource\CustomerGroup.php”

class CustomerGroup extends \Shopware\Components\Api\Resource\CustomerGroup
{
    /**
     * @inheritdoc
     */
    public function getOne($id)
    {
        $result               = parent::getOne($id);
        $result ['attribute'] = $result->getAttribute();

        return $result;
    }
}

“SwagExtendCustomerGroupResource\Resources\services.xml”

<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
    <services>
        <service id="swag_extend_customer_group_resource.customer_group_resource"
                 class="SwagExtendCustomerGroupResource\Components\Api\Resource\CustomerGroup"
                 decorates="shopware.api.customergroup"
                 public="false"
                 shared="false">
        </service>
    </services>
</container>

我期待看到“属性”属性但它没有显示

标签: shopware

解决方案


正如您在原始getOne方法中看到的那样,查询构建器不会选择客户组的属性。

所以如果你想选择属性,你需要完全覆盖这个方法:

public function getOne($id)
{
   $this->checkPrivilege('read');

   if (empty($id)) {
      throw new ApiException\ParameterMissingException('id');
   }

   $builder = $this->getRepository()->createQueryBuilder('customerGroup')
       ->select('customerGroup', 'd', 'attr') // <-- add select
       ->leftJoin('customerGroup.discounts', 'd')
       ->leftJoin('customerGroup.attribute', 'attr') // <-- join attributes
       ->where('customerGroup.id = :id')
       ->setParameter(':id', $id);

   $query = $builder->getQuery();
   $query->setHydrationMode($this->getResultMode());

   /** @var \Shopware\Models\Customer\Group $category */
   $result = $query->getOneOrNullResult($this->getResultMode());

   if (!$result) {
      throw new ApiException\NotFoundException(sprintf('CustomerGroup by id %d not found', $id));
   }

   return $result;
}

来自 Schöppingen 的问候

迈克尔·泰格曼


推荐阅读