2015-08-05 6 views
3

У меня есть два объекта: Product и Feature. Product есть много других Features (отношение один для много). Каждый Feature имеет имя и важный статус (true, если функция важна, false, если нет). Я хочу получить в TWIG все важные функции для моего продукта.Как данные фильтра внутри объекта объекта в Symfony 2 и Doctrine

Решение ниже очень некрасиво:

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 %} 

Я должен фильтровать данные объекта сущности, но как?

// 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) 
    // ... 
} 

ответ

4

Вы можете использовать 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); 
    } 
} 

В прутик

Product: {{ product.name }} 
Important features: 
{% for feature in product.getImportantFeatures() %} 
    - {{ feature.name }} 
{% endfor %} 
+0

Я думаю, вы также можете использовать '{% for featur e в product.importantfeatures%} 'в вашем Twig. –

0

Вы можете сделать это из репозитория

$featureEntityRepository->findBy(array(
    'impoertant' => true, 
    'product' => $product->getId() 
)); 

 Смежные вопросы

  • Нет связанных вопросов^_^