How do I query a table based with HABTM relationship while providing additional conditions in CakePHP?

StackOverflow https://stackoverflow.com/questions/602227

  •  03-07-2019
  •  | 
  •  

Question

How can i do this in CakePHP: I'm using two tables (regions and safaris) having a many-to-many relationship. The tables are joined by another table called regions_safaris (with the fields region_id & safari_id). I want to fetch all safaris meeting a given criteria like durations of 5 days and in a given region. This should be implemented in CakePHP

Was it helpful?

Solution

juma,

Please resist posting multiple times so quickly.

For more reference, please see the Cakebook Has-And-Belongs-To-Many relationship. It is exactly what you're describing. See http://book.cakephp.org/view/83/hasAndBelongsToMany-HABTM

In short, assuming you have the Cake models setup correctly (with the HABTM relationship established between regions, safaris, and regions_safaris; check the 'joinTable' index on the var $hasAndBelongsToMany array, in the models), you would do this:

   class SafariModel extends AppModel
   { 
     var $name = 'Safari';
     var $hasAndBelongsToMany = array( 'Tag'=>array( ..., 'joinTable'=>'regions_safaris', ... );

     function findSafaris( $duration = 5, $region = null )
     {
       return $this->find('all', array('conditions'=>array('Region.region_name'=>$region, 'Safari.duration'=>$duration) );
     }
     ... // rest of class
   }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top