如何在 Symfony 2 和 Doctrine 中过滤实体对象内的数据
我有两个实体:Product
和 Feature
.Product
有许多其他 Features
(一对多的关系).每个Feature
都有一个名称和一个重要的状态(如果特性重要则为真,否则为假).我想在 TWIG 中使用我的产品的所有重要功能.
I have two entities: Product
and Feature
. Product
has many other Features
(relation one to many). Every Feature
has a name and an important status (true if feature is important, false if not). I want to get in TWIG all important features for my product.
下面的解决方案非常难看:
Solution below is very ugly:
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 %}
我必须过滤实体对象中的数据,但如何过滤?
I must filter data in entity object, but how?
// 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
You can use Criteria class to filter out the Arraycollection of related features
class Product {
protected $features; // (oneToMany)
// ...
protected getFeatures() { // default method
return $this->features;
}
protected getImportantFeatures() { // my custom method
$criteria = DoctrineCommonCollectionsCriteria::create()
->where(DoctrineCommonCollectionsCriteria::expr()->eq("important", true));
return $this->features->matching($criteria);
}
}
在树枝中
Product: {{ product.name }}
Important features:
{% for feature in product.getImportantFeatures() %}
- {{ feature.name }}
{% endfor %}
相关文章