3

我有两个实体:ProductFeature. Product还有很多其他Features的(一对多的关系)。每一个Feature都有一个名字和一个重要的状态(如果特性很重要,则为 true,否则为 false)。我想在 TWIG 中获取我产品的所有重要功能。

下面的解决方案非常难看:

Product: {{ product.name }}
Important features:
{% for feature in product.features %}
    {% if feature.important == true %}
        - {{ feature.name }}
    {% endif %}
{% endfor %}

所以我想得到:

Product: {{ product.name }}
Important features:
{% for feature in product.importantFeatures %}
     - {{ feature.name }}
{% endfor %}

我必须过滤实体对象中的数据,但是如何过滤呢?

// MyBundle/Entity/Vehicle.php
class Product {
    protected $features; // (oneToMany)
    // ...
    protected getFeatures() { // default method
        return $this->features;
    }
    protected getImportantFeatures() { // my custom method
        // ? what next ?
    }
}

// MyBundle/Entity/Feature.php
class Feature {
    protected $name;      // (string)
    protected $important; // (boolean)
    // ...
}
4

2 回答 2

5

可以使用Criteria类过滤掉相关特征的 Arraycollection

class Product {
    protected $features; // (oneToMany)
    // ...
    protected getFeatures() { // default method
        return $this->features;
    }
    protected getImportantFeatures() { // my custom method
        $criteria = \Doctrine\Common\Collections\Criteria::create()
                    ->where(\Doctrine\Common\Collections\Criteria::expr()->eq("important", true));
     return $this->features->matching($criteria);
    }
}

在树枝上

Product: {{ product.name }}
Important features:
{% for feature in product.getImportantFeatures() %}
     - {{ feature.name }}
{% endfor %}
于 2015-08-05T17:20:53.690 回答
0

您可以从存储库中执行此操作

$featureEntityRepository->findBy(array(
    'impoertant' => true,
    'product' => $product->getId()
));
于 2015-08-05T17:06:34.663 回答