在laravel中创建包含几行迁移的表


Create table with few rows with migration in laravel

我想创建一个只保存10行数据的表。我如何通过Laravel 5.3中的migration做到这一点?

Laravel 5.3提供了seeding,也结合了model factories。我猜你用的是Eloquent模型而不是query builder。

<标题> 模型工厂

这里有一个来自Laravel的例子(https://laravel.com/docs/5.3/seeding#using-model-factories)

factory(App'User::class, 10)->create();

这段代码通过User Eloquent模型创建了10个假用户。伪用户的声明可以在database/factories/ModelFactory.php中完成。

<标题>播种h1> 是来自Laravel的部分示例(https://laravel.com/docs/5.3/seeding#writing-seeders)。您可以直接从现有的databaseseder调用模型工厂(不需要创建新的种子器)。
<?php
use Illuminate'Database'Seeder;
use Illuminate'Database'Eloquent'Model;
class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
    */
    public function run()
    {
        factory(App'User::class, 10)->create();    
    }
}
<标题> 运行
  • php artisan db:seed在现有表结构
  • 中播种数据
  • php artisan migrate:refresh --seed用于完全重建数据库并运行种子器

完整的文档和示例,参见上面提供的链接。

没有这样的限制。您可以像往常一样创建表,只添加10行。如果您想知道谁应该向表中添加10行,请阅读"播种"。

同样,如果您只有10行,请考虑使用配置文件。你可以这样做:

'my-data' => [
    1 => ['name' => 'John', 'age' => 30],
    2 => ['name' => 'Alan', 'age' => 40],
    ....
],

并使用config('my-config.my-data')

访问该数据

如果您想要一个虚拟数据填充到您的表中,没有任何麻烦,您可以使用fzaninotto的Faker Package。这个过程就像

通过在终端运行以下命令(从项目根目录)安装faker:

composer require fzaninotto/faker

然后在你的routes.php中,你可以像这样推送假条目:

// Just for an example I am using route to demonstrate the general use
Route::get('/customers',function(){
    $faker = Faker'Factory::create();
    $limit = 10; // this value sets number of rows to be created
    // generate data by accessing properties
    for ($i = 0; $i < $limit; $i++) {
        User::create([ 
            'name' => $faker->name,
            'email' => $faker->email,
            'phoneNumber' => $faker->phoneNumber,
        ]);
    }
});

这将在表中创建总共10行和一些虚拟数据。希望对大家有所帮助