2014-01-17 5 views
0

을 찾을 나는 Item 모델 belongsToCategory, ERGO CategoryhasManyItem을 얻었다.CakePHP의이 hasMany의 관련 모델

에서 CategoriesController을 모두 내고 싶습니다. 카테고리는 Item입니다.

내가 이것을 시도,하지만 작동하지 않습니다 :

$category = $this->Category->findById($id); 

:

if($id == null) { 
    throw new NotFoundException(__('404')); 
} 

$this->Category->id = $id; 
if(!$this->Category->exists()) { 
    throw new NotFoundException(__('404')); 
} 

$items = $this->Category->Item->find(); 
$this->set('items',$items); 

답변

1

당신의 모델을 설정하는 경우 제대로 $hasMany$belongsTo 대응으로, 범주를 얻는 것은 기본적으로 충분하다 항목은 $category 배열에 자동으로 포함됩니다. 당신은 debug() 기능을 확인할 수 있습니다

debug($category); 

또한 당신이 매우 유용 Containable 동작을 사용하여 find()을 수행 할 때 검색 할 모델을 연결 정확히 무엇을 필터링 할 수 있습니다.

1

저는 recursive > -1의 팬이 아니므로 다른 방법을 제안합니다.

$items = $this->Category->find('all', array('contain'=>'Item', 
                'recursive'=>-1)); 
$this->set('items',$items); 

또는 간단한

$items = $this->Category->Item->find('all', 
            array('conditions'=>array('category_id'=>$id))); 

귀하의 문제는 채우기 위해 "모든"이 아니라주는 조건을 지정하지 않았다.