播种以使用强制和随机数据填充 table

Seeding to populate a table with mandatory and random data

目标是 table 包含强制性和随机菜单项。

以下情况仅适用于随机项目

Parent table

$parents = [
   ['id' => 1, 'parent' => 'AA'],
   ['id' => 2, 'parent' => 'BB'],
   ['id' => 3, 'parent' => 'CC'],
];

填充菜单table

$menus = [
   ['id' => 1, 'menu' => 'A'],
   ['id' => 2, 'menu' => 'B'],
   ['id' => 3, 'menu' => 'C'],
   ['id' => 4, 'menu' => 'D'],
   ['id' => 5, 'menu' => 'E'],
];

foreach ($menus as $menu) {
   modelMenu::updateOrCreate([ 'id' => $menu['id']], $menu);
}

关系

    $menus = Menu::all();

    Parent::all()->each(function ($parent) use ($menus) { 
        $parent->menus()->attach(
            $menus->random(rand(1, 5))->pluck('id')->toArray()
        ); 
    });

型号

class Parent extends Model
{
   protected $fillable = ['parents'];

   public function menus()
   {
     return $this->hasMany(Menu::class);
   }
}

 class Menu extends Model
 {
  protected $fillable = ['menus'];

  public function parents()
  {
    return $this->belongsTo(Parent::class);
  }
}

我打算实现的是每个 parent 必须有相关的 ids 1 和 2 菜单;

菜单3、4、5随机添加

示例:

Parent AA - menus with ids 1, 2, 5; 
Parent BB - menus with ids 1, 2, 4, 6;
Parent CC - menus with ids 1, 2, 3;

这应该会达到您想要的结果:


$menus = Menu::all()->values();

Parent::all()->each(function ($parent) use ($menus) { 
    $parent->menus()->attach([
        $menus->get(0)->id, 
        $menus->get(1)->id, 
        ...$menus->whereNotIn('id', [1,2])->random(rand(1, 5))->pluck('id')
    ]); 
});


values() 方法 returns 一个带有键的新集合,您可以利用 get(index) 获取第一条和第二条记录,其余基本上是获取随机记录和 whereNotIn('id', [1,2]) 跳过 ID 为 [1, 2] 的记录。