Christopher Francisco
Christopher Francisco

Reputation: 16288

CakePHP find hasMany associated model

I got a Item model that belongsTo a Category, ergo Category hasMany Item.

from the CategoriesController I want to fetch all the Item the category has.

I tried this, but it isn't working:

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);

Upvotes: 0

Views: 171

Answers (2)

Nunser
Nunser

Reputation: 4522

I'm not a fan of recursive > -1 so I propose another way.

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

or the simplest

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

Your problem was not to specify "all" and not giving conditions to fill.

Upvotes: 1

nIcO
nIcO

Reputation: 5001

If your models are setup correctly with corresponding $hasMany and $belongsTo, getting the category is enough by default:

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

The Items will be automatically included in the $category array. You can check it with the debug() function:

debug($category);

Please also note that you can filter exactly what linked models you want to retrieve when you do a find() by using the very useful Containable behavior.

Upvotes: 1

Related Questions