【问题标题】:Count items from relationschip in faker在faker中计算关系芯片中的项目
【发布时间】:2020-10-12 11:07:12
【问题描述】:

我有一个页面模型和一个文本块模型,用于根据需要创建包含尽可能多的文本块的页面。我正在使用 jquery ui 中的 sortable 按迁移表中的position 字段对文本块进行排序。所以每次我创建一个文本块时,位置都会count + 1,从1开始。

现在我正在设置 2 个 faker factory,1 个用于页面,1 个用于在页面上生成虚拟文本块。我想知道如何计算工厂将创建的随机文本块的数量?所以我可以说每次页面工厂创建一个包含几个文本块的页面时,计数器都不会覆盖每个页面的文本块数量。

 $factory->define(Textblock::class, function (Faker $faker) {

return [
    'page_id' => Page::all()->random()->id,
    'title' => $faker->sentence(rand(2, 5)),
    'summary' => $faker->text,
    'position' => // how can i code this ?
    'visible' => $faker->boolean($chanceOfGettingTrue = 50),

]; });

【问题讨论】:

    标签: laravel factory relation faker seeding


    【解决方案1】:

    您可以创建一个 Counter 对象来将所有增量保存在内存中。类似于:

    class Counter
    {
        private static $counters = [];
    
        public static function nextCounterFor($key, $default = 0)
        {
            if (!isset(self::$counters[$key])) {
                if (is_callable($default)) {
                     $default = $default();
                }
                if (!is_int($default)) {
                     throw new \RuntimeException('The default value must be an integer');
                }
                self::$counters[$key] = $default;
            }
    
            return ++self::$counters[$key];
        }
    }
    

    然后您可以使用它为给定的页面 ID 生成新位置。如果还没有定义键,则必须从数据库中获取用于该页面的最后一个位置(如果存在)

    $factory->define(Textblock::class, function (Faker $faker) {
    
      $page = Page::inRandomOrder()->first();
     
      $position = Counter::nextCounterFor($page->id, static function() use ($page) {
           $lastPosition = Textblock::where('page_id', $page->id)->orderBy('position', 'DESC')->first();
           return $lastPosition !== null ? $lastPosition->position : 0;
      });
    
      return [
        'page_id' => $page->id,
        'title' => $faker->sentence(rand(2, 5)),
        'summary' => $faker->text,
        'position' => $position,
        'visible' => $faker->boolean($chanceOfGettingTrue = 50),
      ];
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-13
      • 2021-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多