Chaim
Chaim

Reputation: 2149

How do I get results from a database table based on results from a different table in cakephp?

For example I have the following tables in my database:

And in the People table I have the following columns:

In the Groups table I have the following columns:

Now I want to fetch results from my database to make a list of all the People. So I would use this:

$this->set('people', $this->Person->find("all"));

And obviously in my view I would loop through the returned array and display it. Now I also want to find out for each person in the list what Colour and Group name they are (retrieved from the groups table).

How would I go about this in CakePHP.

Upvotes: 1

Views: 137

Answers (2)

OldWest
OldWest

Reputation: 2385

First make sure your model relationships are defined. Second, you might want to consider using "id" fields for your related tables (I assume you did and maybe just did not include them in your original questions table definitions).

And yes, run debug($this->Person->find("all")) as Elwhis noted to see what your array is dumping out.

And if this is a mission critical application, be sure to use containable instead of recursive to prevent taxing queries to your db.

Upvotes: 4

Elwhis
Elwhis

Reputation: 1261

You have to set the recursive attribute. But I guess it should work with the default value. Put this line in your controller debug($this->Person->find("all")) and check whether the data doesn't already contain you desired group information.

If not, try setting $this->Person->recursive = 1; before calling the find() function

For more information about recursive: http://book.cakephp.org/view/1063/recursive

Upvotes: 3

Related Questions