You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过已翻译属性筛选EntityCollection集合?

如何用EntityCollection的默认filterByProperty函数筛选已翻译字段?

现有默认筛选方法

EntityCollection类提供了filterByProperty方法,用于根据普通属性筛选集合:

public function filterByProperty(string $property, $value)
{
    return $this->filter(
        static function (Entity $struct) use ($property, $value) {
            return $struct->get($property) === $value;
        }
    );
}

需求与现有实现

我需要基于已翻译字段筛选集合,目前已通过自定义Twig扩展实现该功能,但希望直接复用默认的filterByProperty方法。自定义扩展代码如下:

public function filterByTranslatedProperty(EntityCollection $entityCollection, string $property, $value): EntityCollection
{
    return $entityCollection->filter(
        static function (Entity $struct) use ($property, $value) {
            return $struct->getTranslation($property) === $value;
        }
    );
}

解决方案

方案1:扩展Entity的get方法支持翻译字段

如果可以修改Entity类的get方法,让它支持通过参数控制返回翻译后的值,就能直接复用默认的filterByProperty:

// 修改Entity类的get方法
public function get(string $property, bool $useTranslation = false)
{
    if ($useTranslation) {
        return $this->getTranslation($property);
    }
    // 保留原get方法的逻辑
    return $this->properties[$property] ?? null;
}

// 同步扩展filterByProperty方法,添加可选参数
public function filterByProperty(string $property, $value, bool $useTranslation = false)
{
    return $this->filter(
        static function (Entity $struct) use ($property, $value, $useTranslation) {
            return $struct->get($property, $useTranslation) === $value;
        }
    );
}

调用方式:

$filteredCollection = $collection->filterByProperty('title', '目标翻译内容', true);

方案2:扩展EntityCollection类

如果无法修改原EntityCollection类,可以创建子类扩展该方法:

class TranslatableEntityCollection extends EntityCollection
{
    public function filterByProperty(string $property, $value, bool $useTranslation = false)
    {
        if (!$useTranslation) {
            return parent::filterByProperty($property, $value);
        }

        return $this->filter(
            static function (Entity $struct) use ($property, $value) {
                return $struct->getTranslation($property) === $value;
            }
        );
    }
}

之后使用这个子类的实例,就能通过第三个参数控制是否筛选翻译字段。

方案3:直接使用filter方法(备选)

如果不想扩展类,也可以直接调用filter方法实现相同逻辑:

$filteredCollection = $collection->filter(
    static function (Entity $struct) use ($property, $value) {
        return $struct->getTranslation($property) === $value;
    }
);

内容的提问来源于stack exchange,提问作者Alphaegen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 08:30:24