原则 2 从记录查询


Doctrine2 query from record

我有一个模型,其中类别有孩子和父母。产品重新链接到类别。我想从某个类别的子类别中检索产品列表。我想在我的模板中做一些类似于 doctrine1 的事情:

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

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

通常,我将如何从类别对象进行查询(类似于我们在doctrine1中的记录中所做的)?

谢谢!

这样

的事情会达到你想要的吗?

树枝

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

类别.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);
}
// ...

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

控制器.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
    ));
}

类别.php

<?php
protected $latestProducts;
public function getLatestProducts() {
    return $this->latestProducts;
}