tags:

views:

2223

answers:

4

Can a model have multiple tables in CakePHP?

+2  A: 

Guessing from this sentence in the manual:

A model is generally an access point to the database, and more specifically, to a certain table in the database. By default, each model uses the table who's name is plural of its own, i.e. a 'User' model uses the 'users' table.

I don't think so, but you can make relationships maybe thats what you need.

Check this

MrHus
+1  A: 

It can't have multiple tables at the same time..., but you might be able to modify the Model::useTable property to switch the model's table to a different one. Give it a whirl and let us know if it works.

neilcrookes
+1  A: 

Technically, based on the way you're asking the question, not that I know of. Often, though, I'll use relationships to something that might be similar to what you're after. For example, a person has address information that can be dropped in the people table easily enough, but I usually prefer to pull that out because other entities can also have addresses (a business, etc.).

Same idea if you want to implement some kind of pseudo-inheritance model in your DB. For example, volunteers are people, but so are contractors, vendors and employees. The all share certain properties that you might want to store in a people table and others that are unique to the type of person they are.

In each case you have two models, but they work together seamlessly via their associations.

If that's the kind of scenario you're thinking about then a similar approach might work for you although it's not about a model having multiple tables.

Rob Wilkerson
A: 

Hi,

I guess you want to implement some sort of inheritance in the database (that requires to join the data stored in the parent table when retrieving information from the child table). My approach to solve this was using afterFind callback in the child model. I redefined the callback as follows:

function afterFind($results) { foreach ($results as $key => $val) { $fieldRetrieved=$this->query("SELECT field FROM *parent_table* WHERE id={$val['ChildModelName']['id']}"); $results[$key]['ChildModelName']['field']=$fieldRetrieved[0]['*parent_table*']['field']; } return $results; }

In this way I was including the field/s from the parent table to the results obtained from the child table. In this case I've assumed that both tables are index with a field called id and that field, in the child table, is also a foreign key to the parent table (thus creating the pseudo-inheritance).