A student belongs to a school, and to model this relationship we use the school_id field from the students table.
Create a new table named schools:
CREATE TABLE `schools` ( `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, `title` varchar(45) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Create a models/school.php file with the following contents1):
class School extends ActiveModel { }
As an exercise you should create an “add new school” form and the actions that it requires so that you can fill the form with data or you can just edit the database directly and add some school values.
Open models/student.php file and define a variable in the model class:
class Student extends ActiveModel { var $belongs_to = array('school'); }
This will:
schools table.school_id field from students table to match the school the student belongs to.$display_field from the School model to another field.
Now go to the edit page we created in previous tutorial and see that you now have a list of schools to select from when trying to modify student’s details. Please note that TaniPHP keeps the database configuration cached in the session, so it might not “detect” your new table, to fix this add unset($_SESSION); to index.php right after session_start(), so that the cache is purged.
We want to show the school the student belongs to in the index page, so we will modify views/students/index.php. Add another header column called “School” and display $s->School->title in the foreach:
<h1>List of students</h1> <table border="1" width="400"> <tr> <th>ID</th> <th>Name</th> <th>Age</th> <th>School</th> <th>-</th> </tr> <?php foreach($students as $s) {?> <tr> <td><?=$s->id?></td> <td><a href="?controller=students&action=show&id=<?=$s->id?>"><?=$s->name?></a></td> <td><?=$s->age?></td> <td><?=$s->School->title?></td> <td><a href="?controller=students&action=edit&id=<?=$s->id?>">Edit</a></td> </tr> <? } ?> </table>
When you tell a model that it’s linked to another, it will load by default the linked objects in find()/findAll() method calls2).
In our example, in edit action, when creating a new instance of the Student class, the model finds the record in the table and also loads the School model file, then creates an instance of it inside the School object, that holds the associated record from schools table. So $s->School is an instance of the School model that you can operate on as on any other model instance.