使用 Laravel 数据库播种机在 table 行中创建具有相同随机值的数据库播种机

Create database seeder with same random value in a table row with Laravel database seeder

我正在尝试创建一个 table 并在数据库播种器的帮助下使用以下字段填充 table:

前四个字段将被分配随机词,最后一个字段'correct option'将包含前四个中的任何一个。 我找不到任何解决方案来使用 Laravel 数据库播种器。有人可以帮忙吗?

Create a factory and use Faker 生成您想要的随机词

是这样的吗?

在你的工厂或播种机中使用 faker 随机元素功能。

$optionA = $faker->word;
$optionB = $faker->word;
$optionC = $faker->word;
$optionD = $faker->word;

return [
        'option_a' => $optionA,
        'option_b' => $optionB,
        'option_c' => $optionC,
        'option_d' => $optionD,
        'correct_option'   => $faker->randomElement([$optionA,$optionB,$optionC,$optionD]),
];

这听起来像是 JSON 列(用于问题和答案)的理想用例。例如,您可能决定对单个多项选择题有多个有效答案。

在您的迁移中:

// create_questions_table.php
...
$table->json('choices')->default(new Expression('(JSON_ARRAY())'));
$table->json('answer')->default(new Expression('(JSON_ARRAY())'));

来自https://laravel.com/docs/7.x/migrations#column-modifiers

Using an Expression instance will prevent wrapping the value in quotes and allow you to use database specific functions. One situation where this is particularly useful is when you need to assign default values to JSON columns.

然后创建工厂:

// QuestionFactory.php
$factory->define(Location::class, function (Faker $faker) {
    $choices = $faker->words(4);
    $answer = [ $choices[rand(1,4)] ];

    return [
        'choices' => $choices,
        'answer' => $answer,
    ];
});

使用 Laravel 中包含的 Faker 库,我们可以选择 4 个单词并随机分配其中一个作为答案。