:::
13. 利用模型工廠產生隨機題目
- 建立一個模型工廠, 使用 Artisan 命令
make:factory並指定模型來快速建立模型工廠:php artisan make:factory TopicFactory --model=Topic - 這個新的模型工廠將被放置在
/專案/database/factories目錄中。<?php use Faker\Generator as Faker; $factory->define(App\Topic::class, function (Faker $faker) { return [ // ]; }); - 修改一下內容,讓工廠自動產生加法的數學題目及答案(以加法為例):
<?php use Faker\Generator as Faker; $factory->define(App\Topic::class, function (Faker $faker) { $items = [1, 2, 3, 4]; shuffle($items); $random_date = $faker->dateTimeBetween('-3 days', '+3 days'); $num1 = rand(1, 99); $num2 = rand(1, 99); return [ 'topic' => $num1 . " + " . $num2, 'opt' . $items[0] => $num1 + $num2, 'opt' . $items[1] => $num1 . $num2, 'opt' . $items[2] => rand(1, 99), 'opt' . $items[3] => rand(1, 999), 'ans' => $items[0], 'created_at' => $random_date, 'updated_at' => $random_date, ]; }); - 其中
shuffle()是為了給選項隨機排序,並指定第一個選項$items[0]為正確答案,避免答案都是固定的選項。 - 完整的Faker用法可以參考:https://github.com/fzaninotto/Faker
- 這裡有各種方法的使用範例:https://www.cnblogs.com/love-snow/articles/7655450.html
- 若欲產生中文資料,請修改
\專案\vendor\fzaninotto\faker\src\Faker\Factory.php<?php namespace Faker; class Factory { const DEFAULT_LOCALE = 'zh_TW'; - 我們可以利用tinker來測試一下(要離開tinker請輸入
exit)php artisan tinker - 先建立一題試試
factory(App\Topic::class)->make() - 然後建立5題
factory(App\Topic::class,5)->make() - 建立5題並指定exam_id為1,然後存入資料庫:
factory(App\Topic::class,5)->create(['exam_id' => 3]) - 可以利用此方式來建立大量測設內容,若工廠內容有改變,請離開tinker後再重新進入執行。
12-8 測驗與題目的關聯
