:::

16. 建立並執行考試的Model 及 migrate 文件

一、編輯考試的 migrate 檔案

  1. 學生進行考試時,也要有一個表來紀錄學生填答及分數。

  2. 建立Test(測驗)的 Eloquent 模型,以便將一個資料表變成一個物件來操作,並且順便產生 migration 檔案

    php artisan make:model Test --migration
  3. 編輯/專案/database/migrations/日期_create_tests_table.php

    <?php
    
    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;
    
    class CreateTestsTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('tests', function (Blueprint $table) {
                $table->increments('id');
                $table->text('content');
                $table->unsignedInteger('exam_id');
                $table->foreign('exam_id')->references('id')->on('exams');
                $table->unsignedInteger('user_id');
                $table->foreign('user_id')->references('id')->on('users');
                $table->unsignedTinyInteger('score');
                $table->timestamps();
            });
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('tests');
        }
    }
    
  4. content:紀錄此測驗的題目編號及答案
  5. exam_id:對應的測驗編號
  6. user_id:學生編號
  7. score:得分
  8. 最後執行資料庫同步即可建出新的資料表

    php artisan migrate
  9. 資料表:

到GitHub觀看此單元程式異動


:::

書籍目錄

展開 | 闔起

http%3A%2F%2Fcampus-xoops.tn.edu.tw%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbsn%3D37%26tbdsn%3D1159

計數器

今天: 1087108710871087
昨天: 3438343834383438
總計: 7391416739141673914167391416739141673914167391416