```php 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'); } } ``` ``` 4. 此外,一個考試,也一定會有一個考生,所以,我們也順便加入使用者的關聯。 5. 設好後,日後只要取得`$test`資料,就可以順便帶出`$test->exam`測驗資料,以及`$test->user`使用者資料 6. 另外,批次賦值`$fillable`也順便一下,這些通常都是必做的。 ### 二、設定測驗對考試的關聯 1. 從測驗(exam)的角度來看,一個測驗可能會有多(hasMany)考試(test),所以,開啟使用者的模型 `/專案/app/Exam.php`,加入對題目的 `hasMany `關聯: ``` ```php 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'); } } ``` ``` 2. 設定好關聯後,在取得` $exam `內容時,就會自動加入 `$exam->test` 資料陣列,可以輕鬆的取得測試的相關資料。如果有老師想看這個測驗底下有多少考試,就可以很方便的讀出。 3. 完整關聯請參考: [](https://github.com/tad0616/exam56/commit/77987299cd527ea93c07697a7c792c3dc509e9f8)
```php 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'); } } ``` ``` 2. 設定好關聯後,在取得` $exam `內容時,就會自動加入 `$exam->test` 資料陣列,可以輕鬆的取得測試的相關資料。如果有老師想看這個測驗底下有多少考試,就可以很方便的讀出。 3. 完整關聯請參考: [](https://github.com/tad0616/exam56/commit/77987299cd527ea93c07697a7c792c3dc509e9f8)
進階搜尋