Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Many models on single table in cakephp

Tags:

model

cakephp

I am currently trying to manipulate a database with way too many relations. i wont make it complex for you, so here is a very simplified example:

my table (animals): id, type, title

  • 1, big, elephant
  • 2, big, giraffe
  • 3, small, cat
  • 4, small, dog

what i want to do is to have two models "Big" and "Small". "Big" model will only take care of animals with type 'big' (elephant and giraffe), and "Small" model will take care of animals with type 'small' (cat and dog).

is it possible to do?

like image 531
aladine Avatar asked Dec 04 '25 02:12

aladine


1 Answers

Yes, you can create the model called BigAnimal and then define the $useTable = 'animals'; Then define the beforeFind and the beforeSave to set the type to 'big' every time. Then you can do the same for the SmallAnimal model. Here is an example

class BigAnimal extends AppModel {
   var $useTable = 'animals'; 

   function beforeFind($queryData) {
        // set type to big here
   }

   function beforeSave() {
       // set type to big here
   }
}

While this is the way you can accomplish this, it seems it would be better to keep 1 to 1 model to table. Then you could add the necessary functions to query big and little animals all from the same model. It keeps the code a little cleaner. So something like:

class Animal extends AppModel {

   function findBigAnimals() {
       return $this->find('all', array('conditions' => array('type' => 'big')));
   }

   function findSmallAnimals() {
       return $this->find('all', array('conditions' => array('type' => 'small')));
   }

}
like image 111
Chuck Burgess Avatar answered Dec 05 '25 21:12

Chuck Burgess