就像在laravel中一样,我们先使用Migrations创建表,然后使用Seeders来播种表,但并没有得到它的好处,因为我们可以通过正常的方式来做到这一点,只需转到PHPMYADMIN然后我们需要这样做,因为我们为此编写了很多行但是,我们如何证明这些代码行的合理性呢?
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateItemsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('items', function(Blueprint $table)
{
$table->increments('id');
$table->integer('owner_id');
$table->string('name');
$table->boolean('done');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('items');
}
}
确实是由php artisan命令创建了迁移,但是它们的好处是什么?因为我们有另一种选择吗?
与Seeder文件相同,因为我们为此编写了很多行
class ItemTableSeeder extends Seeder{
public function run(){
DB::table('items')->delete();
$items= array(
array(
'owner_id' => '1',
'name' => 'Watch The Spectacular Now',
'done' => True
),
array(
'owner_id' => '2',
'name' => 'Watch Avengers',
'done' => False
),
array(
'owner_id' => '1',
'name' => 'Watch The Iron man',
'done' => False
),
array(
'owner_id' => '1',
'name' => 'Divergent',
'done' => False
),
array(
'owner_id' => '1',
'name' => 'Bat Man',
'done' => False
),
array(
'owner_id' => '1',
'name' => 'X-Men Days Of Future Past',
'done' => False
)
);
DB::table('items')->insert($items);
}
}
最佳答案
迁移和种子是数据库版本控制。想象一下,有一天您会爱上PostgreSQL或MySQL以外的任何东西。然后想象您想对多行数据进行一些测试。您是否要运行PHPMYADMIN的等效表并插入100、1000或10000行?
因此,现在检查一下:
// migration
class CreateCommentsTable extends Migration {
public function up()
{
Schema::create('comments', function(Blueprint $table) {
$table->increments('id');
$table->string('body');
$table->integer('author_id')->unsigned();
$table->integer('post_id')->unsigned();
$table->timestamps();
});
}
// seeder
class CommentsTableSeeder extends Seeder {
public function run()
{
Eloquent::unguard();
$faker = Faker::create();
foreach(range(1, 1000) as $index)
{
Comment::create([
'body' => $faker->sentence(10),
'author_id' => rand(1,20),
'post_id' => rand(1,150)
]);
}
}
Faker
是一个很棒的工具,您可以在这里找到:https://github.com/fzaninotto/Faker现在您需要做的就是运行
artisan migrate --seed
。当然,与自动化种子相比,它具有更多的优势,您可以通过迁移来更改表,以防万一您想要更改架构等。
关于php - Laravel迁移的好处,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23444124/