:::

12-2 建立並執行題目的Model 及 migrate 文件

一、編輯題目的 migrate 檔案

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

    php artisan make:model Topic --migration
  2. 編輯 /專案/database/migrations/日期_create_topics_table.php

    <?php
    
    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;
    
    class CreateTopicsTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('topics', function (Blueprint $table) {
                $table->increments('id');
                $table->string('topic');
                $table->unsignedInteger('exam_id');
                $table->foreign('exam_id')->references('id')->on('exams')->onDelete('cascade');
                $table->string('opt1');
                $table->string('opt2');
                $table->string('opt3');
                $table->string('opt4');
                $table->unsignedTinyInteger('ans');
                $table->timestamps();
            });
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('topics');
        }
    }
  3. topic:題目
  4. exam_id:對應的測驗編號
  5. opt1~opt4:選項1~4
  6. ans:正確解答
  7. 其中 20 行的 onDelete('cascade') 是一個約束條件,也就是當測驗刪除時,連同題目也一併刪除之意。 詳情:https://laravel-china.org/docs/laravel/5.6/migrations/1400#499c95
  8. 最後執行資料庫遷移即可建出新的資料表

    php artisan migrate
  9. 一樣看一下是否有建立出來

到GitHub觀看此單元程式異動


:::

書籍目錄

展開 | 闔起

http%3A%2F%2Fcampus-xoops.tn.edu.tw%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbdsn%3D1158

計數器

今天: 3262326232623262
昨天: 3438343834383438
總計: 7393591739359173935917393591739359173935917393591