从树枝模板过滤关系的最佳方法

时间:2013-09-10 21:30:25

标签: symfony doctrine-orm twig relationship

在我的Symfony2项目中,我有两个实体:Spot和Weather,两个实体之间有一对多关系“weatherReports”。

某些天气预报已过时,因此我想创建一个“activeWeatherRecords”方法来过滤竞价实体中的天气实体。

不幸的是,我看不出怎么做。我们的想法是不从控制器中获取对象,因为Spot对象被收藏,链接到User对象并直接从twig模板访问。

所以问题是:直接从树枝模板过滤关系的最佳方法是什么?

更新09/11/2013

我设法用我的关系中的过滤方法过滤我的关系。

在我的spot实体中,我声明了一个getActiveWeatherRecords()方法:

public function getActiveWeatherReports()
    {
        // Date
        $date = new \DateTime(date('Y-m-d 12:00:00', time()));

        // Criteria
        $criteria = Criteria::create()
            ->where(Criteria::expr()->gte("date", $date))
            ->orderBy(array("date" => Criteria::ASC))
        ;

        return $this->weatherReports->matching($criteria);
    }

我可以从树枝模板中调用此方法,如下所示:

[...]
{% for weatherReport in spot.activeWeatherReports %}
[...]
{% endfor %}
[...]

1 个答案:

答案 0 :(得分:1)

一种方法是创建一个仅获取活动记录的finder方法。您可以将该方法放在Doctrine存储库中,从控制器(或Service Layer)调用它并将其传递给模板。

另一种方法是向您的实体添加filtering method权限。这样您就不必调用单独的方法并将结果传递给模板 - 传递给实体的实体就足够了。