Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
762 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...