我有两个实体:Product
和Feature
。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)
// ...
}
您可以使用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 %}
您可以从存储库
$featureEntityRepository->findBy(array(
'impoertant' => true,
'product' => $product->getId()
));