How filter data inside entity object in Symfony 2 and Doctrine(如何在 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 %}
这篇关于如何在 Symfony 2 和 Doctrine 中过滤实体对象内的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Symfony 2 和 Doctrine 中过滤实体对象内的数据


- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01