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:
为了遵循本指南,您需要:
Access to an Ubuntu 18.04 local machine or development server as a non-root user with sudo privileges. If you’re using a remote server, it’s advisable to have an active firewall installed. To set these up, please refer to our Initial Server Setup Guide for Ubuntu 18.04.
以具有sudo特权的非root用户身份访问Ubuntu 18.04本地计算机或开发服务器。 如果使用的是远程服务器,建议安装活动防火墙。 要进行设置,请参阅我们的Ubuntu 18.04初始服务器设置指南 。
Docker installed on your server, following Step 1 and Step 2 of How To Install and Use Docker on Ubuntu 18.04.
遵循在Ubuntu 18.04上如何安装和使用Docker的 步骤1和步骤2的步骤 ,将Docker安装在服务器上 。
Docker Compose installed on your server, following Step 1 of How To Install Docker Compose on Ubuntu 18.04.
遵循如何在Ubuntu 18.04上安装Docker Compose的 步骤1 ,在您的服务器上安装Docker Compose 。
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
文件现在的样子:
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_DATABASE
, DB_USERNAME
和DB_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 + X
, Y
,然后按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
图像,并引入nginx
和db
服务所需的其他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 exec
。 exec
命令允许我们在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
的类:
<?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.
此类有两种方法: up
和down
。 这两种方法都包含引导程序代码,您可以扩展它们以自定义执行迁移时发生的情况以及回滚时发生的情况。
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
方法现在的样子:
…
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
文件的样子:
<?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
:
<?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
外观:
<?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
表中:
…
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
字段设置为0
或1
的随机值。
This is what the full PlacesTableSeeder
class will look like after all the updates:
在所有更新之后,完整的PlacesTableSeeder
类将如下所示:
<?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
方法:
…
public function run()
{
$this->call(PlacesTableSeeder::class);
}
...
This is how the full DatabaseSeeder
class will look like after the update:
这是完整的DatabaseSeeder
类在更新后的样子:
<?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模型进一步抽象应用程序的数据库架构的更多详细信息。
laravel 数据库迁移