まず、CI で Datamapper を使用すると、'student' テーブルに 'students' という名前を付けた方が簡単になります。次に、結合テーブル 'courses_students' (Shauna に感謝)。モデルは「学生」と「コース」になります。
フォームのコントローラーは次のようになります (理想的には、フォームをビューに配置します)。
function form() {
echo "<form method='post' action='submitForm'>";
echo "<input type='text' name='student_name'>";
echo "<select name='courses[]' multiple='multiple'>";
$c = new Course();
$c->get();
foreach($c as $course) {
echo "<option value='{$course->id}'>{$course->name}</option>";
}
echo "</select>";
echo "<input type='submit' value='Submit'>";
}
フォームを送信するコントローラー (検証または XSS チェックなし):
function submitForm() {
$s = new Student();
$s->name = $this->input->post('student_name');
// an initial save to the Students table, might be omitted
$s->save();
$course_array = $this->input->post('courses');
// loop through the Courses, get them from db, and save the relationship
foreach($course_array as $k=>$v) {
$c = new Course($v);
$s->save($c);
}
}
いくつかの注意: これは簡単で汚い例です。多くのコースが選択されている場合、これらの複数の保存を行うと処理が遅くなる可能性があり、Datamapper を使用して 1 つのステートメントで配列を保存する方法がある可能性がありますが、それを調査する必要があります。