Zaq*_*uPL 3 php doctrine symfony doctrine-orm symfony-2.7
我有两个实体:Product和Feature。Product有很多其他Features(一对多的关系)。每个Feature都有一个名称和一个重要的状态(如果功能很重要则为真,否则为假)。我想为我的产品使用 TWIG 的所有重要功能。
下面的解决方案非常难看:
Product: {{ product.name }}
Important features:
{% for feature in product.features %}
{% if feature.important == true %}
- {{ feature.name }}
{% endif %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
所以我想得到:
Product: {{ product.name }}
Important features:
{% for feature in product.importantFeatures %}
- {{ feature.name }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
我必须过滤实体对象中的数据,但如何过滤?
// 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)
// ...
}
Run Code Online (Sandbox Code Playgroud)
您可以使用Criteria类过滤掉相关特征的 Arraycollection
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);
}
}
Run Code Online (Sandbox Code Playgroud)
在树枝上
Product: {{ product.name }}
Important features:
{% for feature in product.getImportantFeatures() %}
- {{ feature.name }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2476 次 |
| 最近记录: |