2011-02-09 105 views
0

我對CI和Datamapper完全陌生,我想做一件非常簡單的事情。Datamapper:在關係中保存多個值

我有3個表

courses 
students 
students_courses 

我使用這個模型

學生

 <?php 
      class Student extends DataMapper { 
      var $has_many = array('course'); 
      } 

課程

 <?php 
      class Course extends DataMapper { 
      var $has_many = array('student'); 
     } 

一個數據庫,這個控制器添加學生和選擇他們的課程

學生控制器

  function add(){ 

      $estudiante = new Student(); 
      $estudiante->name = $this->input->post('nombre'); 
      $estudiante->save(); 

      $user = new Student(); 
      $curso = new Course(); 


      $user->get_by_name($estudiante->name); 
      $curso->get_by_name($this->input->post('curso')); 

      $user->save($curso); 

      $this->load->view('student/confirm'); 

      } 

,最後,這種形式的看法時,我想從選擇列表中保存一個值

<p> 
     <label for="nombre">Nombre:</label> 
     <input type="text" name="nombre" id="nombre"> 
    </p> 

    <p> 
     <label for="nombre">Curso:</label> 
     <select multiple name="curso" id="curso"> 
      <?php 

      foreach($course_list as $item) { 

      echo "<option value='$item->name'>" . "$item->name" . "</option>"; 
      } 

      ?> 
     </select> 
    </p> 

    <input type="submit" value="submit"> 


<?php echo form_close(); ?> 

所有的偉大工程......但,我必須做些什麼來節省超過一個價值?

謝謝!

回答

2

我認爲你的問題可能與數據庫建模有關。您需要指定StudentCourse之間的多對多關係。

此外,您需要遍歷$this->input->post('curso')以獲得學生可能擁有的所有課程。事情是這樣的:

foreach ($this->input->post('curso') as $entry) 
{ 
    $curso = new Course(); 
    $curso->get_by_name($entry); 
    $user->save($curso); 
} 

我沒有與DataMapper的經驗,但我覺得你的問題是可以解決這樣:)