Tuesday, July 13, 2010

Condition in HABTM , CAKE , Pagination in data from a HABTM relationship

// app/controllers/categories_controller.php
class CategoriesController extends AppController {
public $paginate = array('Product' => array('limit' => 2, 'joins' => array(
array(
'table' => 'categories_products',
'alias' => 'CategoriesProduct',
'type' => 'inner',
'conditions'=> array('CategoriesProduct.product_id = Product.id')
),
array(
'table' => 'categories',
'alias' => 'Category',
'type' => 'inner',
'conditions'=> array(
'Category.id = CategoriesProduct.category_id',
'Category.id' => 1
)
))));

public function index() {
$data = $this->paginate('Product');
debug($data);
exit;
}
}

Output :
Array
(
[0] => Array
(
[Category] => Array
(
[id] => 1
[name] => PHP
)
[Product] => Array
(
[0] => Array
(
[id] => 1
[name] => CakePHP
)
[1] => Array
(
[id] => 2
[name] => Zend
)
[2] => Array
(
[id] => 3
[name] => Symfony
)
)
)
)