在laravel中插入查询

时间:2017-04-21 05:35:24

标签: laravel

我在表中插入虚假记录,但它没有在数据库中移动。您可以查看我的代码: -

 public function up()
    {
        Schema::create('employees', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email',255)->unique();
            $table->string('contact_number');
            $table->timestamps();       
        });

        $faker = Faker\Factory::create();

        $limit = 33;

        for ($i = 0; $i < $limit; $i++) {
            DB::table('employees')->insert([
                'name' => $faker->name,
                'email' => $faker->unique()->email,
                'contact_number' => $faker->phoneNumber,
            ]);
        }
    }

谁能告诉我哪里错了?请帮帮我。

3 个答案:

答案 0 :(得分:0)

如果要将值添加到数据库,则应使用seeder。对于播种机,请点击此处:https://laravel.com/docs/5.4/seeding

答案 1 :(得分:0)

将此逻辑移至seeder

$limit = 33;

for ($i = 0; $i < $limit; $i++) {
    DB::table('employees')->insert([
        'name' => $faker->name,
        'email' => $faker->unique()->email,
        'contact_number' => $faker->phoneNumber,
    ]);
}

然后运行php artisan db:seed命令执行播种机。

答案 2 :(得分:0)

使用 php artisan make:seeder EmployeesSeeder ,而不是将新代码文件写入此代码:

class EmployeesSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker\Factory::create();

        Employee::truncate();

        foreach(range(1, 33) as $index)
        {
            Employee::create([
                'name' => $faker->name,
                'email' => $faker->unique()->email,
                'contact_number' => $faker->phoneNumber,
            ]);
        }                   
    }
}

更多详情Database: Seeding