How can we display another list record inside in listed record using CakePHP?
I have 3 table that consist: (staff,course,attendance)
(Staff)
staff_id | name | passport
------------------------------------------------
1 | A | 123
2 | B | 132
3 | C | 321
(Course)
c_id | name
----------------------
10 | PHP
20 | AJAX
30 | XHTML
(Attendance)
at_id | staff_id | course_id
------------------------------------------------
1 | 1 | 10
2 | 1 | 20
3 | 1 | 30
4 | 2 | 20
5 | 2 | 30
I would like to generate some report to display listed of course that attend by our staff as you can see below:
Name | Course Attend
------------------------------
A | PHP
| AJAX
| XHTML
B | AJAX
| XHTML
Here I use table staff in displaying result and what should I do to get some another fetch result in my column Course Attend that related to attendance table which will be listed all the related result to their staff ids.
My Code:
(ReportController.php)
$view = $this->Staff->find('all');
$this->set('view', $view);
(View – report.ctp)
<table>
<?php foreach($view as $data): ?>
<td>
<?php echo $data['Staff']['name']; ?>
</td>
<td>
<?php // something to do here... ?>
</td>
<?php endforeach ?>
</table>
Any ideas?
It’s not very clear from your question, but it seems to me like you want to display a view that contains information from all the 3 tables.
In this case, you will need to create Model associations.
In the Attendance model:
In the controller, you can add a find(‘all’) query that will retrieve all the rows from Attendance, together with their corresponding Staff and Course rows.
In the view, you can use a foreach loop as usual:
To display the names of the Staff only once, you can add a variable in the view and reset it each time a new Staff row is found. This works if the find(‘all’) query is ordered.
One more suggestion: you should always name your primary keys as ‘id’, not ‘staff_id’ or ‘c_id’, since Cakephp knows how to bind models based on their names. If you create the models ‘the Cakephp way’, you won’t need to specify the ‘foreignKey’ or ‘conditions’ fields when creating associations.