:::
16-1 設定考試與測驗、考生的關聯
一、設定Test的模型及關聯
- 首先進入某個考試時,要能夠判斷學生身份,並且讓原本的題目列表隨機列出10筆,並可送出儲存。
- 在這之前,我們先來設定一下Test的模型及關聯
- 從考試(test)的角度來看,每個考試都有一個所屬(belongsTo)的測驗(exam),所以,開啟題目的模型
/專案/app/Test.php,加入對測驗的belongsTo關聯:class Test extends Model { protected $fillable = [ 'content', 'user_id', 'exam_id', 'score', ]; public function exam() { return $this->belongsTo('App\Exam'); } public function user() { return $this->belongsTo('App\User'); } } - 此外,一個考試,也一定會有一個考生,所以,我們也順便加入使用者的關聯。
- 設好後,日後只要取得
$test資料,就可以順便帶出$test->exam測驗資料,以及$test->user使用者資料 - 另外,批次賦值
$fillable也順便一下,這些通常都是必做的。
二、設定測驗對考試的關聯
- 從測驗(exam)的角度來看,一個測驗可能會有多(hasMany)考試(test),所以,開啟使用者的模型
/專案/app/Exam.php,加入對題目的hasMany關聯:class Exam extends Model { protected $fillable = [ 'title', 'user_id', 'enable', ]; protected $casts = [ 'enable' => 'boolean', ]; public function topics() { return $this->hasMany('App\Topic'); } public function tests() { return $this->hasMany('App\Test'); } } - 設定好關聯後,在取得
$exam內容時,就會自動加入$exam->test資料陣列,可以輕鬆的取得測試的相關資料。如果有老師想看這個測驗底下有多少考試,就可以很方便的讀出。 - 完整關聯請參考:https://laravel-china.org/docs/laravel/5.6/eloquent-relationships/1404
16. 建立並執行考試的Model 及 migrate 文件
