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

Can we create a migration for the data, not just structure of the tables

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

据我了解,laravel 使我们能够创建迁移,我们可以在其中重复相同的过程,而无需手动创建 table 和结构。 我的问题:

同样,

1) 如果我希望我的数据(table 的输入)也以某种方式存储,这样每当我更改数据库中的数据时,也可以将其还原或全部还原也可以重新创建过程。

2) 如果 1 不可能,那么我们能否有办法保存数据库的 "initial" 播种方法。 (所以当我们"factory"重置整个东西时,它也可以自动填充数据库的内容,而不仅仅是数据库的结构)

有相同的参考资料吗?

我希望我能说清楚!

回答 1) 是的,您可以在每次 运行 迁移时手动自动将数据插入表中。

答案2)问题一可以

示例:

public function up()
{
    // Create the table
    Schema::create('users', function($table){
        $table->increments('id');
        $table->string('email', 255);
        $table->string('password', 64);
        $table->boolean('verified');
        $table->string('token', 255);
        $table->timestamps();
    });

    // Insert some stuff
    DB::table('users')->insert(
        array(
            'email' => 'name@domain.com',
            'verified' => true
        )
    );
}

你认为 Laravel 是不可思议的是正确的!那么关于你的第一个问题。

1) If I want that my data (inputs to the table) are also stored in some way, so that whenever i change the data in the database, that can also be reverted back or the whole process can also be recreated.

如果您想重新创建数据,您需要创建一个 table 播种机。为此,只需使用 artisan.

创建播种机和工厂

php artisan make:seeder UsersTableSeeder

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

composer dump-autoload && php artisan db:seed

如果您想在创建模型时同时创建控制器、播种器和工厂,请键入此 artisan 命令。

php artisan make:model User -fa

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

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

图表 1 - 物品工厂示例 (database/factories/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 - 文章播种器示例 (database/seeds/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 - 文章迁移示例 (database/migrations/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

虽然您可以使用迁移文件或种子文件(如上述答案中所述)进行数据迁移,但根据经验,我强烈建议您将此类迁移代码放在种子文件中,而不是迁移文件中.

原因是 运行 单个文件迁移非常困难。迁移设计为 运行 一次全部完成,或自上次迁移完成后逐步 运行 迁移,迁移并非设计为单独挑选,请参阅迁移帮助:

 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

您会注意到 运行 精心挑选的迁移没有可用的选项,您可能希望某天在数据迁移中执行此操作(例如:假设您只是想从一个遗留系统中获取数据table 到另一个 table,将其视为使用夜间 cron 作业或其他方式将数据从事务数据库移动到分析数据库)。

然而,此选项在播种机中可用:

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

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

这使得它比迁移灵活得多(更不用说播种数据就是关于数据的,这更适合您的任务)