如何在Symfony 2和Doctrine中过滤实体对象内的数据 [英] How filter data inside entity object in Symfony 2 and Doctrine
本文介绍了如何在Symfony 2和Doctrine中过滤实体对象内的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个实体:Product
和Feature
. Product
还有许多其他Features
(一对多关系).每个Feature
都有一个名称和重要状态(如果功能很重要,则为true,否则为false).我想获得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)
// ...
}
推荐答案
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 = \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 %}
这篇关于如何在Symfony 2和Doctrine中过滤实体对象内的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文