落叶松迁移后的种子


Laravel seed after migrating

迁移完成后,我是否可以在迁移中添加一些东西来自动为表添加测试数据?

或者您单独播种吗?

您可以使用--seed选项调用migrate:refresh,以便在迁移完成后自动播种:

php artisan migrate:refresh --seed

这将回滚并重新运行所有迁移,然后运行所有种子程序。


另外,您还可以始终使用Artisan::call()从应用程序内部运行手工命令:

Artisan::call('db:seed');

Artisan::call('db:seed', array('--class' => 'YourSeederClass'));

如果你想要特定的种子类。

如果您不想删除现有数据并希望在迁移后进行种子

lukasgeiter的答案对于测试数据是正确的,但运行以下artisan命令

php artisan migrate:refresh --seed

在生产中将刷新您的数据库,删除从前端输入或更新的任何数据。

如果你想在迁移过程中为数据库设定种子(例如,对应用程序进行更新以保留现有数据),比如在种子数据的同时添加一个新的国家/地区表,你可以执行以下操作:

在database/seeds和位置表迁移中创建一个数据库种子程序示例YourSeeder.php

class YourTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tablename', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name',1000);
            $table->timestamps();
            $table->softDeletes();
        });
        $seeder = new YourTableSeeder();
        $seeder->run();
    }
    /**
    * Reverse the migrations.
    *
    * @return void
    */
    public function down()
    {
        Schema::dropIfExists('tablename');
    }
}

如果YourTableSeeder类出现php类未找到错误,请运行composer dump-autoload

虽然lukasgeiter的答案是正确的,但我想详细谈谈你的第二个问题。

还是必须单独播种?

是的。由于您谈论的是测试数据,因此应避免将播种迁移耦合。当然,如果这不是测试数据,而是应用程序数据,那么您总是可以将插入数据作为迁移的一部分。

顺便说一句,如果您想将数据作为测试的一部分进行种子处理,您可以在Laravel测试用例中调用$this->seed()

Laravel Framework 的运行迁移和种子程序特定文件提示

迁移

php artisan migrate --path=/database/migrations/fileName.php

Roolback

php artisan migrate:rollback --path=/database/migrations/fileName.php

刷新

php artisan migrate:refresh --path=/database/migrations/fileName.php

播种机

php artisan db:seed --class=classNameTableSeeder

感谢