Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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.</p> <p>In this case, you will need to create <a href="http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html" rel="nofollow">Model associations</a>.</p> <p>In the <strong>Attendance model:</strong></p> <pre><code>class Attendance extends AppModel { public $hasOne = array( 'Staff' =&gt; array( 'className' =&gt; 'Staff', 'foreignKey' =&gt; false, 'conditions' =&gt; array('Staff.staff_id = Attendance.staff_id') ), 'Course' =&gt; array( 'className' =&gt; 'Course', 'foreignKey' =&gt; false, 'conditions' =&gt; array('Course.c_id = Attendance.course_id') ) ); } </code></pre> <p>In the <strong>controller</strong>, you can add a find('all') query that will retrieve all the rows from Attendance, together with their corresponding Staff and Course rows.</p> <pre><code>$attendance_rows = $this-&gt;Attendance-&gt;find('all', array('order' =&gt; 'Staff.name ASC, Staff.staff_id ASC')); $this-&gt;set("attendance_rows", $attendance_rows); </code></pre> <p>In the <strong>view</strong>, you can use a foreach loop as usual:</p> <pre><code>&lt;table&gt; &lt;?php foreach($attendance_rows as $data): ?&gt; &lt;td&gt; &lt;?php echo $data['Staff']['name']; ?&gt; &lt;/td&gt; &lt;td&gt; &lt;?php echo $data['Course']['name']; ?&gt; &lt;/td&gt; &lt;?php endforeach ?&gt; &lt;/table&gt; </code></pre> <p>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.</p> <pre><code>&lt;table&gt; &lt;?php $temp = null; $no = 1;?&gt; &lt;?php foreach($attendance_rows as $data): ?&gt; &lt;td&gt; &lt;?php if ($temp != $data['Staff']['staff_id']) { echo $no; $no++;} ?&gt; &lt;/td&gt; &lt;td&gt; &lt;?php if ($temp != $data['Staff']['staff_id']) { echo $data['Staff']['name']; $temp = $data['Staff']['staff_id']}; ?&gt; &lt;/td&gt; &lt;td&gt; &lt;?php echo $data['Course']['name']; ?&gt; &lt;/td&gt; &lt;?php endforeach ?&gt; &lt;/table&gt; </code></pre> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload