Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
760 views
in Technique[技术] by (71.8m points)

php - How filter data inside entity object in Symfony 2 and Doctrine

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)
    // ...
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

In twig

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...