Cakephp: Extend search capability to hasMany Relationship

Posted by Chris on Stack Overflow See other posts from Stack Overflow or by Chris
Published on 2010-12-25T09:45:59Z Indexed on 2010/12/25 9:54 UTC
Read the original article Hit count: 173

Filed under:

I have two models:

Car hasMany Passengers

Passenger belongsTo Car

I want to implement a search using Cake Search. The user should input a number and the searchengine should return all cars that have less than this number passengers.

In my search form:

echo $form->input('passengers', array('label' => 'Passengers', 'div' => false));

In my Car model:

   public $filterArgs = array(
      array('name' => 'passengers', 'type' => 'int'),
   );

In the controller:

   public $presetVars = array(
      array('field' => 'passengers', 'type' => 'int')
   }

I thought of adding a function to the model that returns the number of passengers:

 function countPassengers(){
  return(count($this->Car->Passenger)); //Not sure if this works
 }

And how to I implement this search criteria?:

return all Cars where countPassengers()<passenger

© Stack Overflow or respective owner

Related posts about cakephp