2012-02-22 50 views
0

我有3個模型:學生,課程和學生課程。課程'擁有並且擁有許多'學生,學生擁有許多課程,學生課程屬於學生和課程。在學生註冊課程之前,我需要檢查幾件事情(例如:課程是否已滿,過去是否有該學生參加過課程等)。我可以處理函數內部的邏輯,但是我應該在哪個模型下放置該函數?而且,它應該如何被稱爲?我想到了一個辦法是:CakePHP:在哪裏放置這個功能

// Student Model 
public function canSignupForCourse($studentId, $courseId) { 
    // is the course full? 
    // have they signed up before, etc 
    // return either true or false 
} 

// Could it then be called anywhere as: 
if($this->Student->canSignupForCourse($studentId, $courseId)) { 
    // etc 
} 

或者,有沒有更好/更簡單的方法來做到這一點(而且,我需要同時發送的studentid每次courseid)?

回答

2

我認爲最好的辦法是嘗試在模型中實現這些限制作爲驗證規則。

根據你的描述,申請課程的學生是通過創建一個新的StudentCourse完成的,所以這就是你應該儘量符合驗證規則,例如:

// StudentCourse.php 

$validate = array(
    'course_id' => array(
     'rule' => array('maxStudents', 30), 
     'required' => true, 
     'on' => 'create' 
    ) 
) 

function maxStudents($check, $max) { 
    $count = $this->find('count', array(
     'conditions' => array('course_id' => $check['course_id']), 
     'contain' => false 
    )); 
    return $count < $max; 
} 
0

我倒是第一次檢查在這裏手冊中的例子:http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasmany-through-the-join-model

這應該說服你,你應該讓學生hasAndBelongsToMany「當然還有(因爲課程has學生,但學生犯規belongto過程模型中的關係)

然後,您可以定義關係模型類似CourseMembership(如上面的例子鏈接)

然後我會把canSignupForCourse功能在這一模式。不過我可能拆分此功能成幾個獨立的,如courseNotFull和courseNotTakenBefore

然後我把這些功能整合到模型的驗證對象,像這樣:

public $validate = array( 
    'course_id' => array(
     'courseNotFull' => array( 
      'rule' => array('courseNotFull'), 
      'message' => "Course is full", 
     ), 
     'courseNotTakenBefore' => array(
      'rule' => array('courseNotTakenBefore'), 
      'message' => "Student has taken course before", 
     ) 
    ) 
); 

,並確定與示範功能這樣的:

function courseNotFull() { 
    $this->Course->id = $this->data[$this->alias]['course_id']; 
    $course = $this->Course->read(); 

    return $course['Course']['isFull']; 
} 

function courseTakenBefore() { 
    $this->Student->id = $this->data[$this->alias]['student_id']; 
    $this->Course->id = $this->data[$this->alias]['course_id']; 

    $course = $this->Student->Course->findById($this->Course->id); 

    return $course; 
} 

現在,只要你嘗試保存或驗證()CourseMembership,如果是不成功的驗證將返回一個描述性錯誤消息。

+0

使用這個,我將如何去創建一個新的CourseMembership(我如何設置course_id和student_id)? – execv 2012-02-22 23:17:43

+0

與其他型號相同。假設一名學生已經登錄並試圖註冊一門課程。他的學生證可以通過像http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#accessing-the-logged-in-user那樣訪問。 course_id應與帖子數據一起提交。然後在你的控制器中,你可以添加student_id到$ this-> request-> data,並且調用 $ this-> CourseMembership-> create(); $ this-> CourseMembership-> save($ this-> request-> data); 這個很酷的事情是你可以添加額外的信息給特定的會員,例如出席率和成績 – Vigrond 2012-02-23 00:33:52