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 中过滤实体对象内的数据


基础教程推荐
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 如何替换eregi() 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01