Shopware无需修改核心关联自定义属性至产品的方法问询
解决Shopware无需修改核心扩展Product关联的方案
不用修改核心ProductDefinition,你可以通过Shopware官方推荐的**实体扩展(Entity Extension)**机制,非侵入式地给Product实体添加OneToMany关联到你的customAttributes实体,具体步骤如下:
1. 创建Product实体扩展类
新建一个类实现EntityExtensionInterface,专门用于扩展Product实体的关联关系:
<?php namespace YourPluginNamespace\Core\Content\Product\Extension; use Shopware\Core\Content\Product\ProductDefinition; use Shopware\Core\Framework\DataAbstractionLayer\EntityExtension; use Shopware\Core\Framework\DataAbstractionLayer\Field\OneToManyAssociationField; use Shopware\Core\Framework\DataAbstractionLayer\FieldCollection; use YourPluginNamespace\Core\Content\CustomAttributes\CustomAttributesDefinition; class ProductCustomAttributesExtension extends EntityExtension { public function extendFields(FieldCollection $collection): void { // 添加OneToMany关联,对应CustomAttributes里的ManyToOne字段customAttributes2 $collection->add( new OneToManyAssociationField( 'customAttributes', // Product实体中新增的关联名称 CustomAttributesDefinition::class, 'customAttributes2' // 对应CustomAttributesDefinition里关联Product的字段名 ) ); } public function getDefinitionClass(): string { return ProductDefinition::class; } }
2. 注册实体扩展服务
在插件的src/Resources/config/services.yaml中注册这个扩展类,加上Shopware要求的专属标签:
services: YourPluginNamespace\Core\Content\Product\Extension\ProductCustomAttributesExtension: tags: - name: shopware.entity.extension
3. 在事件中添加关联查询
现在你可以在ProductExportProductCriteriaEvent中正常添加这个关联了——之前没生效是因为核心Product实体未识别到该关联,通过实体扩展注册后即可合法调用:
<?php namespace YourPluginNamespace\EventSubscriber; use Shopware\Core\Content\Product\Event\ProductExportProductCriteriaEvent; use Symfony\Component\EventDispatcher\EventSubscriberInterface; class ProductExportSubscriber implements EventSubscriberInterface { public static function getSubscribedEvents(): array { return [ ProductExportProductCriteriaEvent::class => 'addCustomAttributesAssociation', ]; } public function addCustomAttributesAssociation(ProductExportProductCriteriaEvent $event): void { $criteria = $event->getCriteria(); // 添加关联,名称需和扩展类中定义的一致 $criteria->addAssociation('customAttributes'); } }
记得将这个订阅者同样注册为服务。
原理说明
实体扩展是Shopware官方提供的非侵入式扩展核心实体的方案,它通过服务注册动态为核心实体添加字段或关联,完全不需要修改核心文件。注册完成后,customAttributes与Product的关联会被系统识别,后续在任何查询Product的场景中,只要在Criteria里添加customAttributes关联,就能同步获取对应的数据。
内容的提问来源于stack exchange,提问作者O'Niel
相关产品推荐
相关产品推荐

