我们可以为数据创建迁移,而不仅仅是表的结构

时间:2018-05-13 12:36:32

标签: laravel laravel-5 eloquent laravel-5.6

我喜欢laravel因为能够创建迁移。

根据我的理解,laravel为我们提供了创建迁移的能力,我们可以重复相同的过程,而无需手动创建表和结构。 我的问题:

类似地,

1)如果我希望我的数据(表的输入)也以某种方式存储,那么每当我更改数据库中的数据时,也可以恢复它或者也可以重新创建整个过程。

2)如果1不可能,那么我们是否可以保存数据库“初始”种子的方法。 (所以当我们“工厂”重置整个东西时,它也可以自动填充数据库的内容,而不仅仅是数据库的结构)

是否有同样的参考资料?

我希望我能够清楚自己!

2 个答案:

答案 0 :(得分:3)

你认为Laravel令人难以置信是正确的!关于你的第一个问题。

  

1)如果我希望我的数据(表的输入)也以某种方式存储,那么每当我更改数据库中的数据时,也可以恢复它或者也可以重新创建整个过程。

如果要重新创建数据,则需要创建表格播种器。要做到这一点,只需创建一个有工匠的播种机和工厂。

  

php artisan make:seeder UsersTableSeeder

制作播种机后,您可以使用以下命令运行它:

  

composer dump-autoload&& php artisan db:seed

如果您想在制作模型的同时创建控制器,播种机和工厂,请输入此工匠命令。

  

php artisan make:model User -fa

您可以在Laravel文档中查看有关创建种子和工厂的更多信息here

我会创建播种机,而不是弄乱您的迁移文件。这是几个例子。

图表1 - 文章工厂示例(数据库/工厂/ ArticleFactory.php)

<?php

use Faker\Generator as Faker;

$factory->define(App\Article::class, function (Faker $faker) {
    return [
        'title' => $faker->text(50),
        'slug' => $faker->unique()->slug,
        'body' => $faker->text(200),
        'user_id' => rand(1,10),
    ];
});

图表2 - 文章播种机示例(数据库/种子/ ArticleTableSeeder.php)

<?php

use Illuminate\Database\Seeder;

class ArticlesTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\Article::class, 10)->create();
    }
}

图表3 - 文章迁移示例(数据库/迁移/ 2018_05_13_create_articles_table.php)

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateArticlesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('body');
            $table->string('slug');
            $table->integer('media_id')->nullable();
            $table->integer('user_id')->nullable(); // Owner of Article
            $table->timestamps();
            $table->softDeletes();

            $table->index('slug');

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('articles');
    }
}

图表4 - DatabaseTableSeeder.php

    <?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

use Faker\Factory as Faker;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        // Disable all mass assignment restrictions
        Model::unguard();


        // Seeds the Articles
        $this->call(ArticlesTableSeeder::class);

然后要完成一次完整的恢复出厂设置,您需要做的就是键入以下artisan命令:

  

php artisan migrate:db --fresh

     

php artisan db:seed

答案 1 :(得分:1)

尽管您可以使用迁移文件或种子文件(如以上答案中所述)进行数据迁移,但根据经验,我强烈建议您将这样的迁移代码放在种子文件中,而不是迁移文件中。 / p>

原因是运行单个文件迁移非常困难。迁移被设计为一次全部运行,或者自从上一次迁移完成以来逐步运行迁移,迁移不被设计为单独挑选,请参见迁移帮助:

 php artisan migrate --help
Usage:
  migrate [options]

Options:
      --database[=DATABASE]  The database connection to use.
      --force                Force the operation to run when in production.
      --path[=PATH]          The path of migrations files to be executed.
      --pretend              Dump the SQL queries that would be run.
      --seed                 Indicates if the seed task should be re-run.
      --step                 Force the migrations to be run so they can be rolled back individually.
  -h, --help                 Display this help message
  -q, --quiet                Do not output any message
  -V, --version              Display this application version
      --ansi                 Force ANSI output
      --no-ansi              Disable ANSI output
  -n, --no-interaction       Do not ask any interactive question
      --env[=ENV]            The environment the command should run under
  -v|vv|vvv, --verbose       Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Help:
  Run the database migrations

您会注意到没有可供选择的选项来运行手动迁移,您可能需要在某天进行数据迁移(例如:假设您只是想将数据从一个旧表移至另一张表, (例如,使用每晚的Cron作业等将数据从交易数据库移至分析数据库)。

但是此选项在播种机中可用:

php artisan db:seed --help
Usage:
  db:seed [options]

Options:
      --class[=CLASS]        The class name of the root seeder [default: 

与迁移相比,它具有更大的灵活性(更不用说,种子数据全都与数据有关,这更适合您的任务)