这并不是那么微不足道的事情。您需要编写一个插件来实现此目的。
在你的插件中你需要创建订阅者 https://developer.shopware.com/docs/guides/plugins/plugins/plugin-fundamentals/listening-to-events并监听与产品搜索和列表相关的事件。然后,您需要通过添加聚合来更改搜索条件,以及为列出的产品对象设置聚合值的搜索结果。
class CustomListingEventSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
ProductListingCriteriaEvent::class => [
['handleListingCriteria', -101],
],
ProductSearchCriteriaEvent::class => [
['handleListingCriteria', -101],
],
ProductListingResultEvent::class => [
['handleListingResult', 0],
],
ProductSearchResultEvent::class => [
['handleListingResult', 0],
],
];
}
public function handleListingCriteria(ProductListingCriteriaEvent $event): void
{
$criteria = $event->getCriteria();
$criteria->addAggregation(
new TermsAggregation('review_count', 'product.id', null, null, new CountAggregation('review_count', 'product.productReviews.id'))
);
}
public function handleListingResult(ProductListingResultEvent $event): void
{
/** @var TermsResult $aggregation */
foreach ($event->getResult()->getAggregations() as $aggregation) {
if ($aggregation->getName() === 'review_count') {
foreach ($aggregation->getBuckets() as $bucket) {
/** @var SalesChannelProductEntity $product */
$product = $event->getResult()->getEntities()->get($bucket->getKey());
if (!$product) {
continue;
}
// Ideally you should implement you own `Struct` extension
$text = new TextStruct();
$text->setContent((string) $bucket->getResult()->getCount());
$product->addExtension('review_count', $text);
}
}
}
}
}
对于此示例,它将计算与产品相关的所有评论,而不仅仅是那些活跃的评论。您可能还想查看有关的文档如何过滤聚合 https://developer.shopware.com/docs/resources/references/core-reference/dal-reference/aggregations-reference#filter-aggregation.
之后,在产品框的模板中,您应该能够输出每个产品的评论数:
{{ product.extensions.review_count.content }}