How filter data inside entity object in Symfony 2

2019-02-25 10:47发布

问题:

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()
));