8

所以类似于唯一的验证规则(参见:https ://github.com/felixkiss/uniquewith-validator ),我想知道如何生成一个条目,其中一列与另一列是唯一的。我想按如下方式播种我的数据库。

例子:

“步骤”表中有 12 个步骤。每个步骤应该有 5 个类别,每个类别都存储在“step_categories”表中。这些类别中的每一个都分配有一个唯一的订单号 1 到 5,每个“step_id”都是唯一的。

请在此处查看此图像以获取数据库应该是什么样子的示例:https ://imgur.com/a/XYA5yyn

对于上面的图像示例,我必须手动在数据库中创建条目。我不想每次都手动生成它,比如说我犯了一个错误并且不得不回滚迁移。

我正在使用工厂来生成这些数据。所以工厂名称是StepCategoriesFactory.php显然我用文件中的create()方法调用工厂DatabaseSeeder.php

我考虑过在 for 循环中执行此操作,然后我意识到当我调用'step_id' => App\Model::all()->random()->id获取新 ID 时,我无法确保我没有获取我刚刚生成 5 个条目的 ID . 我对 Laravel 真的很陌生,我什至不知道从哪里开始。没有关于 SO 的真实信息,faker 可以将唯一性与另一列一起使用。我该怎么办?

注意:步骤 id 并不总是 1-12。步骤 ID 可能会有所不同,具体取决于步骤是否被删除和重新制作。因此,仅分配step_id等于 1-12 是行不通的。

更新:这是我刚写的一些代码,我认为我在正确的轨道上。也许。我已经抓住了step_id它的number字段,因为它始终是 1-12,并且我已经从条目中抓取了 IID。但现在我被困在如何生成订单 1-5 而不会重复。我还没有运行它,因为它不完整,我知道如果没有正确的订单号它会抛出一个错误。

更新2:我认为我在这里走在正确的轨道上。但是我收到一个未定义的变量错误。当我从匿名函数中放入第一行时,它会将每个条目的顺序重置为“1”。如何使 $autoIncrement 变量可用于匿名函数?播种机在更新之间保持不变。

错误图像:https ://imgur.com/a/ywkd0Lb 终端中出现 Die/Dump 错误的第二张图像:https ://imgur.com/a/rOGRv32

在这里参考这篇文章:https ://laracasts.com/discuss/channels/laravel/model-factory-increment-value-faker?page=1

更新 3:我忘记了use ($autoIncrement)匿名函数的代码行。下面的代码已更新,但现在我收到一个不同的错误,指出订单列具有空值并且无法插入。显然它应该是'1'。即使在我调用 my $autoIncrement->next();which 应该将其增加到 '1' 之后,它仍然根据终端返回 null。但是,当我对其进行死转时,$autoIncrement->current()它会返回 1。奇怪。

更新 3 错误:https ://imgur.com/a/STOmIjF

StepCategoriesFactory.php

use Faker\Generator as Faker;

$autoIncrement = autoIncrement();

$factory->define(App\StepCategory::class, function (Faker $faker) use ($autoIncrement) {
    // Generate Created At and Updated at DATETIME
    $DateTime = $faker->dateTime($max = 'now');
    $autoIncrement->next();
    $order = (int) $autoIncrement->current();

    return [
        // Generate Dummy Data
        'order' =>  $order,
        'name' => $faker->words(4, true),
        'created_at' => $DateTime,
        'updated_at' => $DateTime,
    ];
});

function autoIncrement()
{
    for ($i = 0; $i < 5; $i++) {
        yield $i;
    }
}

编辑:悬赏这个问题,因为我认为这将有助于社区获得详细的答案。我正在寻求帮助来解释如何确保我通过每个循环获取相同的条目。

4

3 回答 3

3

终于解决了!

所以我接受了每个人的答案,并苦苦思索了如何使用 for 循环来创建订单号。1-5。我最后遇到的问题是 $i 变量没有重置。所以在收益率之后,我必须检查 $i 变量是否等于 5,然后将其重置为零。

这是代码!

StepCategories.php

use Faker\Generator as Faker;

$autoIncrement = autoIncrement();

$factory->define(App\StepCategory::class, function (Faker $faker) use ($autoIncrement) {
    // Generate Created At and Updated at DATETIME
    $DateTime = $faker->dateTime($max = 'now');

    // Get the next iteration of the autoIncrement Function
    $autoIncrement->next();
    // Assign the current $i value to a typecast variable.
    $order = (int) $autoIncrement->current();


    return [
        // Generate Dummy Data
        'order' =>  $order,
        'name' => $faker->words(4, true),
        'created_at' => $DateTime,
        'updated_at' => $DateTime,
    ];
});

function autoIncrement()
{
    // Start a loop
    for ($i = 0; $i <= 5; $i++) {
        // Yield the current value of $i
        yield $i;
        // If $i is equal to 5, that must mean the start of a new loop
        if($i == 5) {
            // Reset $i to 0 to start over.
            $i = 0;
        }
    }
}

DatabaseSeeder.php

// Generate Dummy Categories
// Run the factory 12 times
foreach(range(1, 12) as $i) {
    // Generate 5 entries each time
    factory(App\StepCategory::class, 5)->create([
        // Since all steps have a number 1-12 grab the step by the number column and get it's ID
        'step_id' => App\Step::where('number', '=', $i)->first()->id,
    ]);
}

感谢所有帮助过的人!

于 2018-06-04T00:24:47.173 回答
1

抱歉,如果您不理解我的观点,那么我将尝试在代码中进行解释

    use Illuminate\Database\Seeder;


$factory->define(App\StepCategory::class, function (Faker $faker) {
    // Generate Created At and Updated at DATETIME
    $DateTime = $faker->dateTime($max = 'now');
    $step_id = function () {
            return factory('App\Step')->create()->id;
        };

    return [
        // Generate Dummy Data
       'step_id' => $step_id,
        'order' => uniqueOrder($step_id),
        'name' => $faker->words(4, true),
        'created_at' => $DateTime,
        'updated_at' => $DateTime,
    ];
});

function uniqueOrder($step_id)
{
    $unique = rand(1,5);
    do {
       $unique = rand(1,5);
     }
     while(StepCategory::where('step_id', $step_id)->andWhere( 'order', $unique)->exists())

  return $unique;

}
于 2018-06-03T23:51:02.777 回答
0

例如,如果您的 Step 模型名称是 Steps :

$allSteps = Steps::all();
foreach($allSteps as $step){
   for($i=1;$i<6;$i++){
     //insert to table $step->id , $i  for example 
     DB::table('yourTableName')->insert([
           'name'=>'Step '.$step->id.'- Category '.$i , 
           'order'=>$i , 
          'step_id'=>$step->id
     ]);
    }
}
于 2018-06-03T23:25:23.047 回答