使用属于用户的任务播种数据库

时间:2017-12-02 10:12:32

标签: php laravel

我的laravel版本为Laravel Framework 5.5.22

我有以下任务架构:

    Schema::create('tasks', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->integer('user_id')->unsigned();
        $table->timestamps();
    });

在我的TaskTableSeeder课程中,我想为每个user分配一些tasks。 请参阅下面我尝试的内容:

class TaskTableSeeder extends Seeder
{

    public function run()
    {
        $faker = Faker\Factory::create();
        $limit = 25;

        $userIds = DB::table('users')->get('id');      

        for ($i = 0; $i < $limit; $i++) {
            DB::table('tasks')->insert([
                'name' => $faker->sentence(),
                'user_id' => $faker->randomElement($userIds),
            ]);
        }
    }
}

但是,我收到以下错误:

Seeding: UserTableSeeder
Seeding: TaskTableSeeder

In Grammar.php line 124:

  Type error: Argument 1 passed to Illuminate\Database\Grammar::columnize() must be of the type array, string given, call
  ed in C:\Users\marcus\Desktop\Coding Projects\demo_laravel_todo\vendor\laravel\framework\src\Illuminate\Database\Query\
  Grammars\Grammar.php on line 131

有什么建议我做错了吗?

2 个答案:

答案 0 :(得分:2)

您可以传递数组数组,而只在insert函数中传递单数组。更改代码

   for ($i = 0; $i < $limit; $i++) {
        DB::table('tasks')->insert([
            'name' => $faker->sentence(),
            'user_id' => $faker->randomElement($userIds),
        ]);
    }

   $insertData = array();
   for ($i = 0; $i < $limit; $i++) {
        $insertData[] = [
            'name' => $faker->sentence(),
            'user_id' => $faker->randomElement($userIds),
        ];
    }
    DB::table('tasks')->insert($insertData);

请查看以下docs

中的示例
DB::table('users')->insert([
    ['email' => 'taylor@example.com', 'votes' => 0],
    ['email' => 'dayle@example.com', 'votes' => 0]
]);

答案 1 :(得分:1)

您收到错误是因为您正在将字符串传递给randomElement()。您需要将数组传递给randomElement(),因此请使用pluck()toArray()

$userIds = DB::table('users')->pluck('id')->toArray();