2013-02-20 3 views
0

작업

관련 모델의 조건에 따라 데이터 집합을 반환하려고합니다.하위 모델 데이터를 필터링하여 상위 모델 데이터를 제거하는 방법은 무엇입니까?

문제 현재

내가 일치하는 모든 모델 데이터를 반환 함유 성을 사용하지만,이 조건을 포함 일치하는 경우에만 하위 데이터를 반환받을 수있는 가장 가까운. 이는 내 데이터가 제거되는 것이 아니라 기본 모델 데이터를 여전히 포함하므로 이상적이지 않습니다.

예를 들어 ProductCategory 사이의 HABTM 관계를 사용하고 있으며 특정 카테고리의 모든 제품을 찾고 싶습니다.

획기적인 아이디어

기본 방법은 containable을 사용합니다.

$this->Product->find('all', array(
    'contain' => array(
     'Category' => array(
      'conditions' => array(
       'Category.id' => $categoryId 
      ) 
     ) 
    ) 
)); 

그러나 모든 제품이 반환되지만 포함 조건과 일치하지 않는 경우 범주 차원이 제거됩니다.

가장 가까운 지금까지 다음 쿼리를 생성

$this->Product->find('all', array(
    'contain' => false, 
    'joins' => array(
     array(
      'table' => 'categories_products', 
      'alias' => 'CategoriesProduct', 
      'type' => 'LEFT', 
      'conditions' => array(
       'CategoriesProduct.product_id' => 'Product.id' 
      ) 
     ), 
     array(
      'table' => 'categories', 
      'alias' => 'Category', 
      'type' => 'LEFT', 
      'conditions' => array(
       'Category.id' => 'CategoriesProduct.category_id' 
      ) 
     ) 
    ), 
    'conditions' => array(
     'Product.status_id' => 1, 
     'Category.id' => $categoryId 
    ), 
)); 

,

SELECT `Product`.`id`, `Product`.`name`, `Product`.`intro`, `Product`.`content`, `Product`.`price`, `Product`.`image`, `Product`.`image_dir`, `Product`.`icon`, `Product`.`icon_dir`, `Product`.`created`, `Product`.`modified`, `Product`.`status_id` 
FROM `skyapps`.`products` AS `Product` 
LEFT JOIN `skyapps`.`categories_products` AS `CategoriesProduct` ON (`CategoriesProduct`.`product_id` = 'Product.id') 
LEFT JOIN `skyapps`.`categories` AS `Category` ON (`Category`.`id` = 'CategoriesProduct.category_id') 
WHERE `Product`.`status_id` = 1 
AND `Category`.`id` = 12 

이 쿼리는 쿼리를 중단하는 대신에 '의'조인 조건이 인용되고있는 것을 제외하고, 올바른 것입니다.

매뉴얼 쿼리는

SELECT * 
FROM products 
JOIN categories_products ON categories_products.product_id = products.id 
JOIN categories ON categories.id = categories_products.category_id 
WHERE categories.id = 12 

답변

1

문제 내 가입 조건을 정의 된 방식에 누워. 연관 배열이 아니라 오히려 문자열입니다.

 'conditions' => array(
      'CategoriesProduct.product_id = Product.id' 
     ) 

 'conditions' => array(
      'CategoriesProduct.product_id' => 'Product.id' 
     ) 

변경