laravel 数据库迁移_如何在Laravel中使用数据库迁移和种子来抽象数据库设置

laravel 数据库迁移

Migrations and seeders are powerful database utilities provided by the Laravel PHP framework to allow developers to quickly bootstrap, destroy and recreate an application’s database. These utilities help to minimize database inconsistency problems that can arise with multiple developers working on the same application: new contributors need only to run a couple artisan commands to set the database up on a fresh install.

迁移播种机是由提供了强大的数据库实用程序LaravelPHP框架,使开发人员可以快速地引导,破坏并重新创建一个应用程序的数据库。 这些实用程序有助于最大程度地减少多个开发人员在同一个应用程序上工作时可能引起的数据库不一致问题:新的贡献者仅需运行几个artisan命令即可在全新安装中设置数据库。

In this guide, we’ll create migrations and seeders to populate a Laravel demo application’s database with sample data. At the end, you will be able to destroy and recreate your database tables as many times as you want, using only artisan commands.

在本指南中,我们将创建迁移和种子服务器,以使用示例数据填充Laravel演示应用程序的数据库。 最后,您仅需使用artisan命令即可销毁并重新创建数据库表。

先决条件 (Prerequisites)

In order to follow this guide, you’ll need:

为了遵循本指南,您需要:

Note: In this guide, we’ll use a containerized development environment managed by Docker Compose to run the application, but you may also opt to run the application on a LEMP server. To set this up, you can follow our guide on How to Install and Configure Laravel with LEMP on Ubuntu 18.04.

注意 :在本指南中,我们将使用由Docker Compose管理的容器化开发环境来运行该应用程序,但您也可以选择在LEMP服务器上运行该应用程序。 要进行设置,您可以遵循我们的指南,该指南如何在Ubuntu 18.04上使用LEMP安装和配置Laravel

第1步-获取演示应用程序 (Step 1 — Obtaining the Demo Application)

To get started, we’ll fetch the demo Laravel application from its GitHub repository. We’re interested in the tutorial-02 branch, which includes a Docker Compose setup to run the application on containers. In this example, we’ll download the application to our home folder, but you can use any directory of your choice:

首先,我们将从其GitHub存储库中获取演示Laravel应用程序。 我们对tutorial-02分支感兴趣,该分支包括一个Docker Compose设置,用于在容器上运行该应用程序。 在此示例中,我们将应用程序下载到我们的主文件夹中,但是您可以使用您选择的任何目录:

  • cd ~

    光盘〜
  • curl -L https://github.com/do-community/travellist-laravel-demo/archive/tutorial-2.0.1.zip -o travellist.zip

    curl -L https://github.com/do-community/travellist-laravel-demo/archive/tutorial-2.0.1.zip -o travellist.zip

Because we downloaded the application code as a .zip file, we’ll need the unzip command to unpack it. If you haven’t done so recently, update your machine’s local package index:

由于我们将应用程序代码下载为.zip文件,因此需要unzip命令将其解压缩。 如果您最近没有这样做,请更新计算机的本地软件包索引:

  • sudo apt update

    sudo apt更新

Then install the unzip package:

然后安装unzip包:

  • sudo apt install unzip

    sudo apt安装解压缩

Following that, unzip the contents of the application:

然后,解压缩应用程序的内容:

  • unzip travellist.zip

    解压缩travellist.zip

Then rename the unpacked directory to travellist-demo for easier access:

然后将解压后的目录重命名为travellist-demo,以方便访问:

  • mv travellist-laravel-demo-tutorial-2.0.1 travellist-demo

    mv travellist-laravel-demo-tutorial-2.0.1 travellist-demo

In the next step, we’ll create a .env configuration file to set up the application.

在下一步中,我们将创建一个.env配置文件来设置应用程序。

第2步-设置应用程序的.env文件 (Step 2 — Setting Up the Application’s .env File)

In Laravel, a .env file is used to set up environment-dependent configurations, such as credentials and any information that might vary between deployments. This file is not included in revision control.

在Laravel中, .env文件用于设置与环境有关的配置 ,例如凭据以及部署之间可能有所不同的任何信息。 此文件不包含在修订控制中。

Warning: The environment configuration file contains sensitive information about your server, including database credentials and security keys. For that reason, you should never share this file publicly.

警告 :环境配置文件包含有关服务器的敏感信息,包括数据库凭据和安全密钥。 因此,您永远不应公开共享此文件。

The values contained in the .env file will take precedence over the values set in regular configuration files located in the config directory. Each installation on a new environment requires a tailored environment file to define things such as database connection settings, debug options, and the application URL, among other items that may vary depending on which environment the application is running.

.env文件中包含的值将优先于config目录中常规配置文件中设置的值。 在新环境中进行的每个安装都需要定制的环境文件来定义诸如数据库连接设置,调试选项和应用程序URL之类的内容,这些其他项目可能会根据运行应用程序的环境而有所不同。

Navigate to the travellist-demo directory:

导航到travellist-demo目录:

  • cd travellist-demo

    cd travellist-demo

We’ll now create a new .env file to customize the configuration options for the development environment we’re setting up. Laravel comes with an example.env file that we can copy to create our own:

现在,我们将创建一个新的.env文件,以针对要设置的开发环境自定义配置选项。 Laravel带有示例.env文件,我们可以复制.env文件以创建自己的文件:

  • cp .env.example .env

    cp .env.example .env

Open this file using nano or your text editor of choice:

使用nano或您选择的文本编辑器打开此文件:

  • nano .env

    纳米.env

This is how your .env file looks like now:

这是您的.env文件现在的样子:

.env
.env
APP_NAME=Travellist
APP_ENV=dev
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost:8000 

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=db
DB_PORT=3306
DB_DATABASE=travellist
DB_USERNAME=travellist_user
DB_PASSWORD=password
…

The current .env file from the travellist demo application contains settings to use the containerized environment we’ve created with Docker Compose in the last part of this series. You don’t need to change any of these values, but you are free to modify the DB_DATABASE, DB_USERNAME and DB_PASSWORD if you wish, since these are pulled by our docker-compose.yml file automatically to set up the development database. Just make sure the DB_HOST variable remains unchanged, since it references the name of our database service within the Docker Compose environment.

travellist演示应用程序中的当前.env文件包含设置,以使用我们在本系列最后一部分中通过Docker Compose创建的容器化环境。 您不需要更改任何这些值,但是您可以根据需要随意修改DB_DATABASEDB_USERNAMEDB_PASSWORD ,因为它们会被我们docker-compose.yml文件自动docker-compose.yml以设置开发数据库。 只需确保DB_HOST变量保持不变,因为它引用了Docker Compose环境中我们数据库服务的名称。

If you make any changes to the file, make sure to save and close it by pressing CTRL + X, Y, then ENTER.

如果对文件进行了任何更改,请确保通过按CTRL + XY ,然后按ENTER保存并关闭它。

Note: If you have opted to run the application on a LEMP server, you’ll need to change the highlighted values to reflect your own database settings, including the DB_HOST variable.

注意 :如果您选择在LEMP服务器上运行该应用程序,则需要更改突出显示的值以反映您自己的数据库设置,包括DB_HOST变量。

第3步-使用Composer安装应用程序依赖项 (Step 3 — Installing Application Dependencies with Composer)

We’ll now use Composer, PHP’s dependency management tool, to install the application’s dependencies and make sure we’re able to execute artisan commands.

现在,我们将使用PHP的依赖关系管理工具Composer来安装应用程序的依赖关系,并确保我们能够执行artisan命令。

Bring up your Docker Compose environment with the following command. This will build the travellist image for the app service and pull in the additional Docker images required by the nginx and db services, in order to create the application environment:

使用以下命令启动Docker Compose环境。 这将为app服务构建travellist图像,并引入nginxdb服务所需的其他Docker图像,以创建应用程序环境:

  • docker-compose up -d

    docker-compose up -d

   
Output
Creating network "travellist-demo_travellist" with driver "bridge" Building app Step 1/11 : FROM php:7.4-fpm ---> fa37bd6db22a Step 2/11 : ARG user ---> Running in 9259bb2ac034 … Creating travellist-app ... done Creating travellist-nginx ... done Creating travellist-db ... done

This operation might take a few minutes to complete. Once the process is finished, we can run Composer to install the application’s dependencies.

此操作可能需要几分钟才能完成。 该过程完成后,我们可以运行Composer来安装应用程序的依赖项。

To execute composer and other commands in the app service container, we’ll use docker-compose exec. The exec command allows us to execute any command of our choice on containers managed by Docker Compose. It uses the following syntax: docker-compose exec service_name command.

要在app服务容器中执行composer和其他命令,我们将使用docker-compose execexec命令允许我们在Docker Compose管理的容器上执行我们选择的任何命令。 它使用以下语法: docker-compose exec service_name command

Note: In case you have opted to use a LEMP server to run the demo application, you should ignore the docker-compose exec app portion of the commands listed throughout this guide. For example, instead of running the following command as it’s written, you would just run:

注意 :如果您选择使用LEMP服务器运行演示应用程序,则应忽略本指南中列出的命令的docker-compose exec app部分。 例如,您可以直接运行以下命令,而不必运行编写时的以下命令:

  • composer install

    作曲家安装

To execute composer install in the app container, run:

要在app容器中执行composer install ,请运行:

  • docker-compose exec app composer install

    docker-compose exec app composer安装


   
Output
Loading composer repositories with package information Installing dependencies (including require-dev) from lock file Package operations: 85 installs, 0 updates, 0 removals - Installing doctrine/inflector (1.3.1): Downloading (100%) - Installing doctrine/lexer (1.2.0): Downloading (100%) - Installing dragonmantank/cron-expression (v2.3.0): Downloading (100%) …

When Composer is finished installing the application’s dependencies, you’ll be able to execute artisan commands. To test that the application is able to connect to the database, run the following command which will clean up any pre-existing tables:

当Composer完成安装应用程序的依赖项时,您将能够执行artisan命令。 要测试该应用程序是否能够连接到数据库,请运行以下命令,该命令将清除所有先前存在的表:

  • docker-compose exec app php artisan db:wipe

    docker-compose exec app php artisan db:wipe

This command will drop any pre-existing tables on the configured database. If it ran successfully and the application is able to connect to the database, you’ll see output like this:

此命令将删除已配置数据库上的所有现有表。 如果运行成功,并且应用程序能够连接到数据库,您将看到以下输出:


   
Output
Dropped all tables successfully.

Now that you have installed the application dependencies with Composer, you can use the artisan tool to create migrations and seeders.

现在,您已经使用Composer安装了应用程序依赖项,您可以使用artisan工具创建迁移和种子。

第4步-创建数据库迁移 (Step 4 — Creating Database Migrations)

The artisan command line tool that ships with Laravel contains a series of helper commands that can be used to manage the application and bootstrap new classes. To generate a new migration class, we can use the make:migration command as follows:

Laravel随附的artisan命令行工具包含一系列帮助程序命令,可用于管理应用程序和引导新类。 要生成新的迁移类,我们可以使用make:migration命令,如下所示:

  • docker-compose exec app php artisan make:migration create_places_table

    docker-compose exec app php artisan make:migration create_places_table

Laravel infers the operation to be executed (create), the name of the table (places), and whether this migration will create a new table or not, based on the descriptive name provided to the make:migration command.

Laravel根据提供给make:migration命令的描述性名称,推断要执行的操作( create ),表名( places )以及此迁移是否将创建新表。

You’ll see output similar to this:

您将看到类似于以下的输出:


   
Output
Created Migration: 2020_02_03_143622_create_places_table

This will generate a new file in the application’s database/migrations directory. The timestamp included in the auto-generated file is used by Laravel to determine in which order migrations should be executed.

这将在应用程序的database/migrations目录中生成一个新文件。 Laravel使用自动生成的文件中包含的时间戳来确定执行迁移的顺序。

Use your text editor of choice to open the generated migration file. Remember to replace the highlighted value with your own migration file name:

使用您选择的文本编辑器打开生成的迁移文件。 请记住用您自己的迁移文件名替换突出显示的值:

  • nano database/migrations/2020_02_03_143622_create_places_table.php

    纳米数据库/迁移/ 2020_02_03_143622_create_places_table.php

The generated migration file contains a class called CreatePlacesTable:

生成的迁移文件包含一个名为CreatePlacesTable的类:

database/migrations/2020_02_03_143622_create_places_table.php
database / migrations / 2020_02_03_143622_create_places_table.php
<?php

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

class CreatePlacesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('places', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->timestamps();
        });
    }

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

This class has two methods: up and down. Both methods contain bootstrap code that you can extend to customize what happens when that migration is executed and also what happens when it is rolled back.

此类有两种方法: updown 。 这两种方法都包含引导程序代码,您可以扩展它们以自定义执行迁移时发生的情况以及回滚时发生的情况。

We’ll modify the up method so that the places table reflects the structure we’re already using in the current application’s version:

我们将修改up方法,以便places表反映当前应用程序版本中已经在使用的结构:

  • id: primary key field.

    id :主键字段。

  • name: name of the place.

    name :地点名称。

  • visited: whether or not this place was already visited.

    visited :这个地方是否已经被访问过。

The Laravel schema builder exposes methods for creating, updating and deleting tables in a database. The Blueprint class defines the table’s structure and it provides several methods to abstract the definition of each table field.

Laravel模式构建器公开了用于创建,更新和删除数据库中表的方法。 Blueprint类定义了表的结构,并提供了几种方法来抽象化每个表字段的定义。

The auto-generated code sets up a primary id field called id. The timestamps method creates two datetime fields that are automatically updated by the underlying database classes when data is inserted or updated within that table. In addition to these, we’ll need to include a name and a visited field.

自动生成的代码设置了一个名为id的主id字段。 timestamps方法创建两个datetime字段,当在该表中插入或更新数据时,基础数据库类会自动更新这些datetime字段。 除了这些,我们还需要包括一个name和一个visited字段。

Our name field will be of type string, and our visited field will be set with the boolean type. We’ll also set a default value of 0 for the visited field, so that if no value is passed, it means the place was not visited yet. This is how the up method will look like now:

我们的name字段将为string类型,而我们的visited字段将设置为boolean类型。 我们还将为visited字段设置默认值0 ,这样,如果未传递任何值,则表示尚未访问该地点。 这是up方法现在的样子:

database/migrations/2020_02_03_143622_create_places_table.php
database / migrations / 2020_02_03_143622_create_places_table.php
…
    public function up()
    {
        Schema::create('places', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name', 100);
            $table->boolean('visited')->default(0);
            $table->timestamps();
        });
    }
…

Note: You can find the full list of available column types in the Laravel documentation.

注意 :您可以在Laravel文档中找到可用列类型的完整列表。

After including the two highlighted lines on your own migration script, save and close the file.

在自己的迁移脚本中包括突出显示的两行之后,保存并关闭文件。

Your migration is now ready to be executed via artisan migrate. However, that would only create an empty table; we also need to be able to insert sample data for development and testing. In the next step, we’ll see how to do that using database seeders.

现在,您可以通过artisan migrate执行artisan migrate 。 但是,那只会创建一个空表。 我们还需要能够插入示例数据以进行开发和测试。 在下一步中,我们将看到如何使用数据库播种器执行此操作。

步骤5 —创建数据库种子 (Step 5 — Creating Database Seeders)

A seeder is a special class used to generate and insert sample data (seeds) in a database. This is an important feature in development environments, since it allows you to recreate the application with a fresh database, using sample values that you’d otherwise have to manually insert each time the database is recreated.

播种机是一个特殊的类,用于在数据库中生成和插入样本数据(种子)。 这是开发环境中的一项重要功能,因为它允许您使用示例值重新创建一个新的数据库,否则每次创建数据库时都必须手动插入这些示例值。

We’ll now use the artisan command to generate a new seeder class for our places table called PlacesTableSeeder:

现在,我们将使用artisan命令来为我们的新的播种机类places称为表PlacesTableSeeder

  • docker-compose exec app php artisan make:seeder PlacesTableSeeder

    docker-compose exec app php artisan make:seeder PlacesTableSeeder

The command will create a new file called PlacesTableSeeder.php inside the database/seeds directory. Open that file using your text editor of choice:

该命令将在database/seeds目录中创建一个名为PlacesTableSeeder.php的新文件。 使用您选择的文本编辑器打开该文件:

  • nano database/seeds/PlacesTableSeeder.php

    纳米数据库/种子/PlacesTableSeeder.php

This is what the auto-generated PlacesTableSeeder.php file looks like:

这是自动生成的PlacesTableSeeder.php文件的样子:

database/seeds/PlacesTableSeeder.php
数据库/种子/PlacesTableSeeder.php
<?php

use Illuminate\Database\Seeder;

class PlacesTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //
    }
}

Our new seeder class contains an empty method named run. This method will be called when the db:seed Artisan command is executed.

我们的新seeder类包含一个名为run的空方法。 执行db:seed Artisan命令时将调用此方法。

We need to edit the run method in order to include instructions to insert sample data in the database. We’ll use the Laravel query builder to streamline this process.

我们需要编辑run方法,以包括在数据库中插入样本数据的说明。 我们将使用Laravel查询构建器来简化此过程。

The Laravel query builder offers a fluent interface for database operations such as inserting, updating, deleting, and retrieving data. It also introduces safeguards against SQL injection attacks. The query builder is exposed by the DB facade - a static proxy to underlying database classes in the service container.

Laravel查询构建器为数据库操作(如插入,更新,删除和检索数据)提供了流畅的界面。 它还引入了针对SQL注入攻击的防护措施。 查询生成器被暴露DB 门面静态代理在服务容器数据库类标的- 。

To get started, we’ll create a static class variable to hold all the sample places we want to insert into the database as an array. This will allow us to use a foreach loop to iterate through all values, inserting each one in the database using the query builder.

首先,我们将创建一个静态类变量,以保存要作为数组插入数据库的所有示例位置。 这将使我们能够使用foreach循环遍历所有值,并使用查询生成器将每个值插入数据库中。

We’ll call this variable $places:

我们将这个变量称为$places

database/seeds/PlacesTableSeeder.php
数据库/种子/PlacesTableSeeder.php
<?php

use Illuminate\Database\Seeder;

class PlacesTableSeeder extends Seeder
{
    static $places = [
        'Berlin',
        'Budapest',
        'Cincinnati',
        'Denver',
        'Helsinki',
        'Lisbon',
        'Moscow',
        'Nairobi',
        'Oslo',
        'Rio',
        'Tokyo'
    ];
…

Next, we’ll need to include a use statement at the top of our PlacesTableSeeder class to facilitate referencing the DB facade throughout the code:

接下来,我们需要在PlacesTableSeeder类的顶部包含一个use语句,以方便在整个代码中引用DB外观:

database/seeds/PlacesTableSeeder.php
数据库/种子/PlacesTableSeeder.php
<?php

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class PlacesTableSeeder extends Seeder
…

We can now iterate through the $places array values using a foreach loop, and insert each one in our places table using the query builder:

现在,我们可以使用foreach循环遍历$places数组值,并使用查询生成器将每个插入到我们的places表中:

database/seeds/PlacesTableSeeder.php
数据库/种子/PlacesTableSeeder.php
…
    public function run()
    {
        foreach (self::$places as $place) {
            DB::table('places')->insert([
                'name' => $place,
                'visited' => rand(0,1) == 1
            ]);
        }
    }

The foreach loop iterates through each value of the $places static array. At each iteration, we use the DB facade to insert a new row at the places table. We set the name field to the name of the place we just obtained from the $places array, and we set the visited field to a random value of either 0 or 1.

foreach循环遍历$places静态数组的每个值。 在每次迭代中,我们使用DB外观在places表中插入新行。 我们将name字段设置为刚从$places数组获得的地点的名称,并将visited字段设置为01的随机值。

This is what the full PlacesTableSeeder class will look like after all the updates:

在所有更新之后,完整的PlacesTableSeeder类将如下所示:

database/seeds/PlacesTableSeeder.php
数据库/种子/PlacesTableSeeder.php
<?php

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class PlacesTableSeeder extends Seeder
{
    static $places = [
        'Berlin',
        'Budapest',
        'Cincinnati',
        'Denver',
        'Helsinki',
        'Lisbon',
        'Moscow',
        'Nairobi',
        'Oslo',
        'Rio',
        'Tokyo'
    ];

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        foreach (self::$places as $place) {
            DB::table('places')->insert([
                'name' => $place,
                'visited' => rand(0,1) == 1
            ]);
        }
    }
}

Save and close the file when you’re done making these changes.

完成这些更改后,保存并关闭文件。

Seeder classes aren’t automatically loaded in the application. We need to edit the main DatabaseSeeder class to include a call to the seeder we’ve just created.

播种器类不会自动加载到应用程序中。 我们需要编辑主要的DatabaseSeeder类,以包含对我们刚刚创建的播种器的调用。

Open the database/seeds/DatabaseSeeder.php file using nano or your favorite editor:

使用nano或您喜欢的编辑器打开database/seeds/DatabaseSeeder.php文件:

  • nano database/seeds/DatabaseSeeder.php

    纳米数据库/种子/DatabaseSeeder.php

The DatabaseSeeder class looks like any other seeder: it extends from the Seeder class and has a run method. We’ll update this method to include a call to PlacesTableSeeder.

DatabaseSeeder类的外观类似于任何其他播种器:它是从Seeder类扩展的,并且具有run方法。 我们将更新此方法以包括对PlacesTableSeeder的调用。

Update the current run method inside your DatabaseSeeder class by deleting the commented-out line and replacing it with the following highlighted code:

通过删除注释行并将其替换为以下突出显示的代码,来更新DatabaseSeeder类中的当前run方法:

database/seeds/DatabaseSeeder.php
数据库/种子/DatabaseSeeder.php
…
    public function run()
    {
        $this->call(PlacesTableSeeder::class);
    }
...

This is how the full DatabaseSeeder class will look like after the update:

这是完整的DatabaseSeeder类在更新后的样子:

database/seeds/DatabaseSeeder.php
数据库/种子/DatabaseSeeder.php
<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $this->call(PlacesTableSeeder::class);
    }
}

Save and close the file when you’re done updating its content.

完成文件内容更新后,保存并关闭文件。

We have now finished setting up both a migration and a seeder for our places table. In the next step, we’ll see how to execute them.

现在,我们已经完成了为places表设置迁移和种子服务器的工作。 在下一步中,我们将看到如何执行它们。

第6步-运行数据库迁移和种子 (Step 6 — Running Database Migrations and Seeders)

Before proceeding, we need to make sure your application is up and running. We’ll set up the application encryption key and then access the application from a browser to test the web server.

在继续之前,我们需要确保您的应用程序已启动并正在运行。 我们将设置应用程序加密密钥,然后从浏览器访问该应用程序以测试Web服务器。

To generate the encryption key required by Laravel, you can use the artisan key:generate command:

要生成Laravel所需的加密密钥,可以使用artisan key:generate命令:

  • docker-compose exec app php artisan key:generate

    docker-compose exec app php artisan key:generate

Once the key has been generated, you’ll be able to access the application by pointing your browser to your server hostname or IP address on port 8000:

生成密钥后,您可以通过将浏览器指向端口8000上的服务器主机名或IP地址来访问应用程序:

http://server_host_or_ip:8000

You’ll see a page like this:

您会看到这样的页面:

That means the application is able to connect to the database, but it couldn’t find a table called places. We’ll create the places table now, using the following migrate artisan command:

这意味着该应用程序能够连接到数据库,但是找不到名为places的表。 现在,我们将使用以下migrate artisan命令创建places表:

  • docker-compose exec app php artisan migrate

    docker-compose exec app php artisan migration

You’ll get output similar to this:

您将获得类似于以下的输出:


   
Output
Migration table created successfully. Migrating: 2014_10_12_000000_create_users_table Migrated: 2014_10_12_000000_create_users_table (0.06 seconds) Migrating: 2014_10_12_100000_create_password_resets_table Migrated: 2014_10_12_100000_create_password_resets_table (0.06 seconds) Migrating: 2019_08_19_000000_create_failed_jobs_table Migrated: 2019_08_19_000000_create_failed_jobs_table (0.03 seconds) Migrating: 2020_02_10_144134_create_places_table Migrated: 2020_02_10_144134_create_places_table (0.03 seconds)

You’ll notice that a few other migrations were executed along with the create_places_table migration we’ve set up. These migrations are auto generated when Laravel is installed. Although we won’t be using these additional tables now, they will be needed in the future when we expand the application to have registered users and scheduled jobs. For now, you can just leave them as is.

您会注意到,还有一些其他迁移与我们设置的create_places_table迁移一起执行。 安装Laravel时会自动生成这些迁移。 尽管我们现在将不再使用这些附加表,但是将来在我们将应用程序扩展为具有注册用户和计划作业时,将需要它们。 现在,您可以保持原样。

At this point our table is still empty. We need to run the db:seed command to seed the database with our sample places:

此时我们的表仍然是空的。 我们需要运行db:seed命令以使用示例位置为数据库添加种子:

  • docker-compose exec app php artisan db:seed

    docker-compose exec app php artisan db:seed

This will run our seeder and insert the sample values we defined within our PlacesTableSeeder class. You’ll see output similar to this:

这将运行我们的播种器,并将我们在PlacesTableSeeder类中定义的样本值插入。 您将看到类似于以下的输出:


   
Output
Seeding: PlacesTableSeeder Seeded: PlacesTableSeeder (0.06 seconds) Database seeding completed successfully.

Now, reload the application page on your browser. You’ll see a page similar to this:

现在,在浏览器上重新加载应用程序页面。 您会看到类似以下页面:

Whenever you need to start from scratch, you can drop all your database tables with:

每当需要从头开始时,都可以使用以下方法删除所有数据库表:

  • docker-compose exec app php artisan db:wipe

    docker-compose exec app php artisan db:wipe


   
Output
Dropped all tables successfully.

To run the app migrations and seed the tables in a single command, you can use:

要运行应用迁移并在单个命令中为表添加种子,可以使用:

  • docker-compose exec app php artisan migrate --seed

    docker -compose exec app php artisan migration --seed


   
Output
Migration table created successfully. Migrating: 2014_10_12_000000_create_users_table Migrated: 2014_10_12_000000_create_users_table (0.06 seconds) Migrating: 2014_10_12_100000_create_password_resets_table Migrated: 2014_10_12_100000_create_password_resets_table (0.07 seconds) Migrating: 2019_08_19_000000_create_failed_jobs_table Migrated: 2019_08_19_000000_create_failed_jobs_table (0.03 seconds) Migrating: 2020_02_10_144134_create_places_table Migrated: 2020_02_10_144134_create_places_table (0.03 seconds) Seeding: PlacesTableSeeder Seeded: PlacesTableSeeder (0.06 seconds) Database seeding completed successfully.

If you want to roll back a migration, you can run:

如果要回滚迁移,可以运行:

  • docker-compose exec app php artisan migrate:rollback

    docker-compose exec app php artisan migration:rollback

This will trigger the down method for each migration class inside the migrations folder. Typically, it will remove all the tables that were created through migration classes, leaving alone any other tables that might have been manually created. You’ll see output like this:

这将触发migrations文件夹中每个迁移类的down方法。 通常,它将删除通过迁移类创建的所有表,仅保留可能手动创建的任何其他表。 您将看到如下输出:


   
Output
Rolling back: 2020_02_10_144134_create_places_table Rolled back: 2020_02_10_144134_create_places_table (0.02 seconds) Rolling back: 2019_08_19_000000_create_failed_jobs_table Rolled back: 2019_08_19_000000_create_failed_jobs_table (0.02 seconds) Rolling back: 2014_10_12_100000_create_password_resets_table Rolled back: 2014_10_12_100000_create_password_resets_table (0.02 seconds) Rolling back: 2014_10_12_000000_create_users_table Rolled back: 2014_10_12_000000_create_users_table (0.02 seconds)

The rollback command is especially useful when you’re making changes to application models and a db:wipe command can’t be used - for instance, if multiple systems depend on the same database.

当您更改应用程序模型并且不能使用db:wipe命令时,例如,如果多个系统依赖同一数据库,则rollback命令特别有用。

结论 (Conclusion)

In this guide, we’ve seen how to use database migrations and seeders to facilitate setting up development and testing databases for a Laravel 6 application.

在本指南中,我们已经了解了如何使用数据库迁移和播种器来促进为Laravel 6应用程序设置开发和测试数据库。

As a next step, you might want to check the Laravel documentation for more details on how to use the query builder, and how to use Eloquent models to abstract your application’s database schema even further.

下一步,您可能需要查看Laravel文档,以获取有关如何使用查询生成器以及如何使用Eloquent模型进一步抽象应用程序的数据库架构的更多详细信息。

翻译自: https://www.digitalocean.com/community/tutorials/how-to-use-database-migrations-and-seeders-to-abstract-database-setup-in-laravel

laravel 数据库迁移

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页
评论
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值