Basic sorting with HABTM relation in CakePHP

Written: Jul 26th 2009, 23:23

After struggling with doing a basic filter pattern on my new Portfolio section, I found the clues I needed in this tutorial. Here is the basic function.


function index($cat = null) {

if($cat == null) { // If no category chosen, just use the basic paginate function $portfolios = $this->paginate(); } else { // Set basic params with conditions form $this->paginate $params = array( ‘contain’ => false, ‘fields’ => array(‘DISTINCT (Portfolio.id) as id’), ‘conditions’ => $this->paginate[‘conditions’], ‘joins’ => array() );

// Add the search on the habtm relations table $joins1 = array( ‘table’ => $this->Portfolio->tablePrefix.‘portfolios_categories_portfolios’, ‘alias’ => ‘CategoriesPortfolio’, ‘type’ => ‘inner’, ‘foreignKey’ => false, ‘conditions’=> array(‘CategoriesPortfolio.portfolio_id = Portfolio.id’) ); $joins2 = array( ‘table’ => $this->Portfolio->tablePrefix.‘portfolios_categories’, ‘alias’ => ‘Category’, ‘type’ => ‘inner’, ‘foreignKey’ => false, ‘conditions’=> array( ‘Category.id = CategoriesPortfolio.category_id’, ‘Category.slug’ => $cat ) ); array_push($params[‘joins’], $joins1); array_push($params[‘joins’], $joins2);

$tmp = array(); foreach ($this->Portfolio->find(‘all’, $params) as $row) { array_push($tmp, $row[‘Portfolio’][‘id’]); } // Final paginate query with the Portfolio ID’s as ‘scope’ $portfolios = $this->paginate(null, array(‘Portfolio.id’ => $tmp)); } // Send var to the view $this->set(‘portfolios’, $portfolios);
}

Back to posts list