2014-12-13 3 views
0

나는 카테고리에 어린이와 부모가있는 모델이 있습니다. 카테고리에 연결된 제품. 특정 카테고리의 하위 항목에서 제품 목록을 검색하고 싶습니다.Doctrine2 쿼리 레코드에서

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

그러나 나는 내 카테고리 오브젝트에 카테고리 저장소 개체를 전달할 필요로하는 방법을 모르는, 그리고 난이 확신 : 나는 내 템플릿에 doctrine1 유사한 일을 생각 좋은 생각이 아닙니다.

일반적으로 카테고리 객체 (doctrine1의 레코드에서와 비슷한 방식으로)에서 어떻게 쿼리합니까?

감사합니다.

답변

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; 
} 
+0

덕분에, 거의 아니지만 꽤) 나는 최신 10 개 제품은 모든 하위 범주에서 사용 가능한 검색하는 것을 시도하고있다. '같은 제품'SELECT * 어디에서 category_id date_add DESC LIMIT 10 – poulping

+0

에 의해 주문 @poulping 나는 내 대답에 PHP 코드를 편집했습니다 :) – paulgv

+0

나는 문제가 그것이 카테고리에 반복된다는 것, 그것 먼저 하위 카테고리를 반복하고 각각에 대해 최신 카테고리를 가져옵니다. 그러나 전 세계적으로 최신 제품을 주문하지는 않을 것입니다. 그러나 나는 올바른 길을 가고 있다고 믿습니다. 나는 모든 하위 범주에서 모든 제품을 가져 와서 제품 날짜별로 다시 정렬해야합니다. – poulping

관련 문제