Þaw
Þaw

Reputation: 2057

How to perform this query in CakePHP?

I have Rooms table and Residents table. every Room has different number of Residents, so my table is something like this:

Rooms

+-------------------+
| room_id | room_no |
+-------------------+
|   0001  |    5    |
|   0002  |    6    |
+-------------------+

Residents

+-------------------------------+
| user_id | user_name | room_id |
+-------------------------------+
|  0123   |   John    |  0001   |
|  0110   |   Gwen    |  0002   |
|  0020   |   Kim     |  0002   |
+-------------------------------+

So how to perform the query in Controller and then display it in view that would output like this?

Room 1 - Residents
+----------+
| 1 | John |
+----------+

Room 2 - Residents
+----------+
| 1 | Gwen |
| 2 | Kim  |
+----------+

Thanks in advance.

Note: I've already established proper associations my problem is on how to display it to the view as what I expected it to be.

Upvotes: 0

Views: 57

Answers (3)

Onasus
Onasus

Reputation: 240

Find out more at: http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasmany . I used to debug in my .ctp this way.

<?php echo debug($rooms) ?>

You could see the associations before you could parse them. Or use the so called debugkit available at github

Upvotes: 0

Garry
Garry

Reputation: 595

you need to first create an association in Room Model

var $hasMany=array('Resident'); 

After that in controller you can do this

$residents=$this->Room->find('all');

Upvotes: 1

Ben Hitchcock
Ben Hitchcock

Reputation: 1378

Set your Room model to HasMany residents, and then in the paginate call index action of your Room controller you will need to set recursive to 1.

In your Room index view you will need to loop through $room['Resident'] to show the residents.

Upvotes: 0

Related Questions