I have 2 classes – Students and Groups with many-to-many relationship. On a student page, I want to show all his details and list all groups he belongs to, delimited by comma.
This is my Students controller:
class Students extends Controller {
function __construct() {
parent::__construct();
}
function index() {
$this->get_all_students();
}
function get_all_students() {
$s = new Student();
$data['students'] = $s->select('id, name, email')->get();
$this->load->view('students', $data);
}
function view($id) {
$s = new Student();
$s->get_by_id($id);
$s->groups->get();
$data['student'] = $s;
$this->load->view('student_view', $data);
}
}
I can get student’s details like this in student_view:
Name: <?php echo $student->name; ?>
E-mail: <?php echo $student->email; ?>
Groups:
<?php foreach ($student->groups as $group) : ?>
<?php echo anchor("/groups/$group->id", $group->name) ?>
<?php endforeach; ?>
So, how can I list groups delimited by comma? I tried adding group names to an array in the controller and then just <?php echo implode(', ', $groups); ?> in the view. But this way I cannot make a link using group IDs.
1 Answer