Codeigniter和Datamapper的基本CRUD操作

时间:2011-02-07 21:56:48

标签: codeigniter codeigniter-datamapper

我是Codeigniter和Datamapper的新手,我有一个非常基本的问题,我自己在文档中搜索无法解答。

我有一个非常简单的数据库,包含3个表:

 student
 courses
 student_courses

现在,我理解如何处理关系,使用CI进行CRUD操作等等......但是如何使用必须由用户填写的表单来建立学生与课程之间的关系?

想象一下,我有一个用户必须填写学生姓名并选择两门或更多课程的表格......控制器的外观如何?

非常感谢

1 个答案:

答案 0 :(得分:3)

首先,使用带有CI的Datamapper,如果您将“学生”表命名为“学生”,则会更容易。然后连接表'courses_students'(谢谢Shauna)。那么你的模型将是“学生”和“课程”。

表单的控制器可能是这样的(理想情况下,您将表单放在View中):

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将数组保存在一个语句中,但我需要研究它。

相关问题