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


基础教程推荐
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 使用 PDO 转义列名 2021-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01