How filter data inside entity object in Symfony 2 and Doctrine

北慕城南 提交于 2019-12-02 00:31:06

问题


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

So I want to get:

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

回答1:


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 = \Doctrine\Common\Collections\Criteria::create()
                    ->where(\Doctrine\Common\Collections\Criteria::expr()->eq("important", true));
     return $this->features->matching($criteria);
    }
}

In twig

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



回答2:


You can do it from repository

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


来源:https://stackoverflow.com/questions/31838216/how-filter-data-inside-entity-object-in-symfony-2-and-doctrine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!