Laravel:迁移与为生产数据播种 [英] Laravel : Migrations & Seeding for production data

查看:25
本文介绍了Laravel:迁移与为生产数据播种的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序需要一个预先注册的数据集才能工作.所以我需要在设置应用程序时将它们插入到数据库中.

My application needs a pre registered data set to work. So i need to insert them in the database when i set up the application.

Laravel 提出了两种机制:

  • 数据库迁移 : 他们允许团队修改数据库架构并保持最新当前模式状态的日期."
  • 数据库播种 : Laravel 还包括一个简单的方法来播种你的带有使用种子类的测试数据的数据库."
  • Database migrations : "They allow a team to modify the database schema and stay up to date on the current schema state."
  • Database seeding : "Laravel also includes a simple way to seed your database with test data using seed classes."

当我阅读此描述时,这些解决方案似乎都不适用.

When I read this description, none of these solutions seems to be adapted.

在 stackoverflow 上提出了类似的问题已回答.答案建议使用数据库播种器通过检测当前环境来填充数据库:

A similar question has been asked on stackoverflow and answered. The answer proposes to use the a database seeder to populate the database by detecting the current environment :

<?php

class DatabaseSeeder extends Seeder {

    public function run()
    {
            Eloquent::unguard();

            if (App::environment() === 'production')
            {
                $this->call('ProductionSeeder');
            }
            else
            {
                $this->call('StagingSeeder');
            }
    }

}

当然,这个解决方案有效.但我不确定这样做是否正确,因为通过使用播种机插入数据,您将失去迁移机制提供的所有优势(数据库升级、回滚......)

Of course, this solution works. But i am not sure that it is the right way to do this, because by inserting data using seeders you are losing all the advantages provided by the migration mechanism (database upgrate, rollback...)

我想知道在这种情况下最佳做法是什么.

I want to know what is the best practice in this case.

推荐答案

Laravel 开发是关于自由的.因此,如果您需要为生产数据库播种并认为 DatabaseSeeder 是最好的选择,为什么不呢?

Laravel development is about freedom. So, if you need to seed your production database and think DatabaseSeeder is the best place to do so, why not?

好的,seeder 主要用于测试数据,但您会看到有些人照原样使用它.

Okay, seeder is mainly to be used with test data, but you'll see some folks using it as you are.

我将这种重要的种子视为我迁移的一部分,因为这是我的数据库表中不可能出现的东西,并且每次我部署新版本的应用程序时都会运行 artisan migrate,所以我就这么做

I see this important kind of seed as part of my migration, since this is something that cannot be out of my database tables and artisan migrate is ran everytime I deploy a new version of my application, so I just do

php artisan migrate:make seed_models_table

并在其中创建我的种子:

And create my seedind stuff in it:

public function up()
{
    $models = array(
        array('name' => '...'),
    );

    DB::table('models')->insert($models);
}

这篇关于Laravel:迁移与为生产数据播种的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆