从记录中查询Doctrine2

时间:2014-12-13 22:24:42

标签: php symfony doctrine-orm

我有一个类别有孩子和父母的模型。 产品与一个类别相关联。 我想从某个类别的孩子中检索产品列表。 我想在我的模板中做类似于doctrine1的事情:

{% for category in productsByCategories %}
    <h2>{{ category.label }}</h2>
    <ul class="products-list">
    {% for product in category.getLatestProductFromChildCategories() %}

但是我不知道怎么做,因为我需要将类别存储库对象传递给我的类别对象,我相信这不是一个好主意。

一般来说,我如何从类别对象中查询(类似于我们在doctrine1中的记录中的做法)?

谢谢!

1 个答案:

答案 0 :(得分:1)

这样的事情会实现你想要的吗?

<强>枝条

{% for category in productsByCategories %}
    <h2>{{ category.label }}</h2>
    <ul class="products-list">
    {# Loop through child categories #}
    {% for child in category.children %}
        {# Get products from the current child category #}
        {% for product in child.latestProducts %}
            <li>{{ product }}</li>
        {% endfor %}
    {% endfor %}
{% endfor %}

<强> Category.php

<?php
// ...
public function latestProducts() {
    $length = 10;
    if ($this->products->count() < $length) $length = $this->products->count();
    $offset = $this->products->count() - $length;
    return $this->products->slice($offset, $length);
}
// ...

我想您也可以尝试查询控制器中的最新产品。

<强> Controller.php这样

<?php
public function showAction() {
    // ...
    $em = $this->getDoctrine()->getManager();
    // Get the main categories, then loop through them
    foreach ($categories as $category) {
        $childrenIds = array();
        foreach ($categories->getChildren() as $child) {
            array_push($childrenIds, $child->getId());
        }
        // Get the latest products using DQL
        $products = $em->createQuery('SELECT p FROM Application\ProductBundle\Entity\Product p WHERE p.category_id IN (?1) ORDER BY date_add DESC')
                        ->setParameter(1, $childrenIds)
                        ->setMaxResults(10);
        $category->setLatestProducts($products);
    }
    // ...
    return $this->render($template, array(
        'productsByCategories' => $categories
    ));
}

<强> Category.php

<?php
protected $latestProducts;

public function getLatestProducts() {
    return $this->latestProducts;
}