资讯专栏INFORMATION COLUMN

Laravel从已有数据库表生成对应的migration和seed文件

dack / 3667人阅读

摘要:扩展

扩展

https://github.com/Xethron/mi...

https://github.com/orangehill...

migrations-generator

Generate Laravel Migrations from an existing database, including indexes and foreign keys!

Upgrading to Laravel 5.4

Please note that the Laravel 4 Generator edits have been moved to https://github.com/xethron/Laravel-4-Generators.git to update compatibility.

Laravel 5 installation

The recommended way to install this is through composer:

composer require --dev "xethron/migrations-generator"

In Laravel 5.5 the service providers will automatically get registered.

In older versions of the framework edit config/app.php and add this to providers section:

WayGeneratorsGeneratorsServiceProvider::class,
XethronMigrationsGeneratorMigrationsGeneratorServiceProvider::class,

If you want this lib only for dev, you can add the following code to your app/Providers/AppServiceProvider.php file, within the register() method:

public function register()
{
    if ($this->app->environment() !== "production") {
        $this->app->register(WayGeneratorsGeneratorsServiceProvider::class);
        $this->app->register(XethronMigrationsGeneratorMigrationsGeneratorServiceProvider::class);
    }
    // ...
}

Notes:

Thanks to @jamisonvalenta, you can now generate Migrations in Laravel 5!

feature/laravel-five-stable was forked from way/generators 3.0.3 and was made Laravel 5.0 ready. Jeffrey Way has discontinued support for Laravel 5, so the other artisan generate: commands may not have been made 5.0 compatible. Investigate the artisan make: commands for substitutes, contribute to Laravel to extend generation support, or fix it and submit a PR to jamisonvalenta/feature/laravel-five-stable.

Laravel 4 installation

Run the following composer command:

composer require --dev "xethron/migrations-generator:~1.3.0"

Next, add the following service providers:

"WayGeneratorsGeneratorsServiceProvider",
"XethronMigrationsGeneratorMigrationsGeneratorServiceProvider",

And you"re set. To double check if its working, run php artisan, and look for the command migrate:generate

Usage

To generate migrations from a database, you need to have your database setup in Laravel"s Config.

Run php artisan migrate:generate to create migrations for all the tables, or you can specify the tables you wish to generate using php artisan migrate:generate table1,table2,table3,table4,table5. You can also ignore tables with --ignore="table3,table4,table5"

Laravel Migrations Generator will first generate all the tables, columns and indexes, and afterwards setup all the foreign key constraints. So make sure you include all the tables listed in the foreign keys so that they are present when the foreign keys are created.

You can also specify the connection name if you are not using your default connection with --connection="connection_name"

Run php artisan help migrate:generate for a list of options.

Check out Chung Tran"s blog post for a quick step by step introduction: Generate Migrations from an existing database in Laravel 4

iSeed

Inverse seed generator (iSeed) is a Laravel package that provides a method to generate a new seed file based on data from the existing database table.

Installation

1) Add orangehill/iseed to your composer file.

Laravel 5

For Laravel 5 installation edit your project"s composer.json file to require orangehill/iseed.

"require": {
    "orangehill/iseed": "dev-master"
}
Laravel 5 versions less than 5.3.8

For Laravel 5 versions that are less than 5.3.8 edit your project"s composer.json file to require 2.2 version:

"require": {
    "orangehill/iseed": "2.2"
}
Laravel 4

If you wish to install it on Laravel 4 you should require 1.1 version:

"require": {
    "orangehill/iseed": "1.1"
}

2) Update Composer from the CLI:

composer update
Laravel 5 versions less than 5.5

3) Add the service provider by opening a app/config/app.php file, and adding a new item to the providers array.

OrangehillIseedIseedServiceProvider::class
Artisan command options [table_name]

Mandatory parameter which defines which table/s will be used for seed creation.
Use CSV notation for multiple tables. Seed file will be generated for each table.

Examples:

php artisan iseed my_table
php artisan iseed my_table,another_table
force

Optional parameter which is used to automatically overwrite any existing seeds for desired tables

Example:
The following command will overwrite UsersTableSeeder.php if it already exists in laravel"s seeds directory.

php artisan iseed users --force
dumpauto

Optional boolean parameter that controls the execution of composer dump-autoload command. Defaults to true.

Example that will stop composer dump-autoload from execution:

php artisan iseed users --dumpauto=false
clean

Optional parameter which will clean app/database/seeds/DatabaseSeeder.php before creating new seed class.

Example:

php artisan iseed users --clean
database

Optional parameter which specifies the DB connection name.

Example:

php artisan iseed users --database=mysql2
max

Optional parameter which defines the maximum number of entries seeded from a specified table. In case of multiple tables, limit will be applied to all of them.

Example:

artisan iseed users --max=10
exclude

Optional parameter which accepts comma separated list of columns that you"d like to exclude from tables that are being exported. In case of multiple tables, exclusion will be applied to all of them.

Example:

artisan iseed users --exclude=id
artisan iseed users --exclude=id,created_at,updated_at
prerun

Optional parameter which assigns a laravel event name to be fired before seeding takes place. If an event listener returns false, seed will fail automatically.
You can assign multiple preruns for multiple table names by passing an array of comma separated DB names and respectively passing a comma separated array of prerun event names.

Example:
The following command will make a seed file which will fire an event named "someEvent" before seeding takes place.

artisan iseed users --prerun=someEvent

The following example will assign someUserEvent to users table seed, and someGroupEvent to groups table seed, to be executed before seeding.

artisan iseed users,groups --prerun=someUserEvent,someGroupEvent

The following example will only assign a someGroupEvent to groups table seed, to be executed before seeding. Value for the users table prerun was omitted here, so users table seed will have no prerun event assigned.

artisan iseed users,groups --prerun=,someGroupEvent
postrun

Optional parameter which assigns a laravel event name to be fired after seeding takes place. If an event listener returns false, seed will be executed, but an exception will be thrown that the postrun failed.
You can assign multiple postruns for multiple table names by passing an array of comma separated DB names and respectively passing a comma separated array of postrun event names.

Example:
The following command will make a seed file which will fire an event named "someEvent" after seeding was completed.

artisan iseed users --postrun=someEvent

The following example will assign someUserEvent to users table seed, and someGroupEvent to groups table seed, to be executed after seeding.

artisan iseed users,groups --postrun=someUserEvent,someGroupEvent

The following example will only assign a someGroupEvent to groups table seed, to be executed after seeding. Value for the users table postrun was omitted here, so users table seed will have no postrun event assigned.

artisan iseed users,groups --postrun=,someGroupEvent
noindex

By using --noindex the seed can be generated as a non-indexed array.
The use case for this feature is when you need to merge two seed files.

Example:

artisan iseed users --noindex
Usage

To generate a seed file for your users table simply call: Iseed::generateSeed("users", "connectionName", "numOfRows");. connectionName and numOfRows are not required arguments.

This will create a file inside a /database/seeds (/app/database/seeds for Laravel 4), with the contents similar to following example:

truncate();
        DB::table("users")->insert(array (
            0 =>
            array (
                "id" => "1",
                "email" => "admin@admin.com",
                "password" => "$2y$10$tUGCkQf/0NY3w1l9sobGsudt6UngnoVXx/lUoh9ElcSOD0ERRkK9C",
                "permissions" => NULL,
                "activated" => "1",
                "activation_code" => NULL,
                "activated_at" => NULL,
                "last_login" => NULL,
                "persist_code" => NULL,
                "reset_password_code" => NULL,
                "first_name" => NULL,
                "last_name" => NULL,
                "created_at" => "2013-06-11 07:47:40",
                "updated_at" => "2013-06-11 07:47:40",
            ),
            1 =>
            array (
                "id" => "2",
                "email" => "user@user.com",
                "password" => "$2y$10$ImNvsMzK/BOgNSYgpjs/3OjMKMHeA9BH/hjl43EiuBuLkZGPMuZ2W",
                "permissions" => NULL,
                "activated" => "1",
                "activation_code" => NULL,
                "activated_at" => NULL,
                "last_login" => "2013-06-11 07:54:57",
                "persist_code" => "$2y$10$C0la8WuyqC6AU2TpUwj0I.E3Mrva8A3tuVFWxXN5u7jswRKzsYYHK",
                "reset_password_code" => NULL,
                "first_name" => NULL,
                "last_name" => NULL,
                "created_at" => "2013-06-11 07:47:40",
                "updated_at" => "2013-06-11 07:54:57",
            ),
        ));
    }

}

This command will also update /database/seeds/DatabaseSeeder.php (/app/database/seeds/DatabaseSeeder.php for Laravel 4) to include a call to this newly generated seed class.

If you wish you can define custom iSeed template in which all the calls will be placed. You can do this by using #iseed_start and #iseed_end templates anywhere within /database/seeds/DatabaseSeeder.php (/app/database/seeds/DatabaseSeeder.php for Laravel 4), for example:


Alternatively you can run Iseed from the command line using Artisan, e.g. php artisan iseed users. For generation of multiple seed files comma separated list of table names should be send as an argument for command, e.g. php artisan iseed users,posts,groups.

In case you try to generate seed file that already exists command will ask you a question whether you want to overwrite it or not. If you wish to overwrite it by default use --force Artisan Command Option, e.g. php artisan iseed users --force.

If you wish to clear iSeed template you can use Artisan Command Option --clean, e.g. php artisan iseed users --clean. This will clean template from app/database/seeds/DatabaseSeeder.php before creating new seed class.

You can specify db connection that will be used for creation of new seed files by using Artisan Command Option --database=connection_name, e.g. php artisan iseed users --database=mysql2.

To limit number of rows that will be exported from table use Artisan Command Option --max=number_of_rows, e.g. php artisan iseed users --max=10. If you use this option while exporting multiple tables specified limit will be applied to all of them.

To (re)seed the database go to the Terminal and run Laravel"s db:seed command (php artisan db:seed).

Please note that some users encountered a problem with large DB table exports (error when seeding from table with many records). The issue was solved by splitting input data into smaller chunks of elements per insert statement. As you may need to change the chunk size value in some extreme cases where DB table has a large number of columns, the chunk size is configurable in iSeed"s config.php file:

"chunk_size" => 500 // Maximum number of rows per insert statement

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/28517.html

相关文章

  • laravel入门

    摘要:开发根目录测试分为单元测试和功能测试创建一个文件执行测试测试前清除配置缓存运行单个测试用例小提示在开发与进行交互的第三方扩展包时,最好选择注入契约而不使用。 参考https://laravelacademy.org/ 概念 单词 契约Contract 就是接口 repository 仓库(封装数据访问,可以搜索:repository模式) Container 容器 ServicePr...

    韩冰 评论0 收藏0
  • laravel artisan

    摘要:用法显示当前的帮助信息不输出任何信息显示当前版本强制输出禁用输出不进行交互运行环境详细输出普通更加详细可用命令全局命令清除编译生成的文件,相当于的反操作将站点设为维护状态显示当前运行环境来源于 laravel artisan 用法 $ php artisan Laravel Framework version 5.1.46 (LTS) Usage: command [options] ...

    Betta 评论0 收藏0
  • Laravel 中缓存驱动速度比较

    摘要:我们很容易修改缓存驱动方式。这样的话,我们甚至根本不必检查缓存是否过期。与驱动相比,和的速度更快,所以建议在项目较大时使用外部缓存驱动。结论使用文件数据库作为驱动,两者在速度上没有很明显的区别。所以投资高速缓存是值得的。 showImg(https://segmentfault.com/img/remote/1460000014057714?w=1440&h=720); 缓存是web开...

    go4it 评论0 收藏0
  • Laravel 5 系列入门教程(一)【最适合中国人 Laravel 教程】

    摘要:原文发表在我的个人网站系列入门教程一最适合中国人的教程本教程示例代码见大家在任何地方卡住,最快捷的解决方式就是去看我的示例代码。在此我推荐一个全量中国镜像。 原文发表在我的个人网站:Laravel 5 系列入门教程(一)【最适合中国人的 Laravel 教程】 本教程示例代码见:https://github.com/johnlui/Learn-Laravel-5 大...

    EscapedDog 评论0 收藏0
  • f-admin——基于Laravel框架开发基础权限后台系统

    摘要:基础权限后台本项目码云,目前已在公司产品应用,运行在数个客户服务器内。基础权限后台是一套基于框架开发的系统,不需要开发者重复不必要的工作,就可以实现后台功能的快速开发,其主要特点包括集成,安装使用方便。 f-admin基础权限后台 ❤️ 本项目 GitHub / Gitee(码云),目前已在公司产品应用,运行在数个客户服务器内。 f-admin基础权限后台是一套基于Laravel框架开...

    Ali_ 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<