Table of Contents
1、简介
2、编写填充器
3、运行填充器
Home Backend Development PHP Tutorial [ Laravel 5.2 文档 ] 数据库 -- 填充数据

[ Laravel 5.2 文档 ] 数据库 -- 填充数据

Jun 23, 2016 pm 01:19 PM

1、简介

Laravel包含了一个简单方法来填充数据库——使用填充类和测试数据。所有的填充类都位于 database/seeds目录。填充类的类名完全由你自定义,但最好还是遵循一定的规则,比如可读性,例如 UserTableSeeder等等。安装完 Laravel 后,会默认提供一个 DatabaseSeeder类。从这个类中,你可以使用 call方法来运行其他填充类,从而允许你控制填充顺序。

2、编写填充器

要生成一个填充器,可以通过 Artisan 命令 make:seeder。所有框架生成的填充器都位于 database/seeders目录:

php artisan make:seeder UserTableSeeder
Copy after login

一个填充器类默认只包含一个方法: run。当Artisan命令 db:seed运行时该方法被调用。在 run方法中,可以插入任何你想插入数据库的数据,你可以使用查询构建器手动插入数据,也可以使用 Eloquent模型工厂。

举个例子,让我们修改 Laravel 安装时自带的 DatabaseSeeder类,添加一个数据库插入语句到 run方法:

<?phpuse DB;use Illuminate\Database\Seeder;use Illuminate\Database\Eloquent\Model;class DatabaseSeeder extends Seeder{    /**     * 运行数据库填充     *     * @return void     */    public function run()    {        DB::table('users')->insert([            'name' => str_random(10),            'email' => str_random(10).'@gmail.com',            'password' => bcrypt('secret'),        ]);    }}
Copy after login

使用模型工厂

当然,手动指定每一个模型填充的属性是很笨重累赘的,取而代之的,我们可以使用模型工厂来方便的生成大量的数据库记录。首先,查看模型工厂文档来学习如何定义工厂,定义工厂后,可以使用帮助函数 factory来插入记录到数据库。

举个例子,让我们创建50个用户并添加关联关系到每个用户:

/** * 运行数据库填充 * * @return void */public function run(){    factory('App\User', 50)->create()->each(function($u) {        $u->posts()->save(factory('App\Post')->make());    });}
Copy after login

调用额外的填充器

在 DatabaseSeeder类中,你可以使用 call方法执行额外的填充类,使用 call方法允许你将数据库填充分解成多个文件,这样单个填充器类就不会变得无比巨大,只需简单将你想要运行的填充器类名传递过去即可:

/*** 运行数据库填充** @return void*/public function run(){    Model::unguard();    $this->call(UserTableSeeder::class);    $this->call(PostsTableSeeder::class);    $this->call(CommentsTableSeeder::class);    Model::reguard();}
Copy after login

3、运行填充器

编写好填充器类之后,可以使用 Artisan 命令 db:seed来填充数据库。默认情况下, db:seed命令运行可以用来运行其它填充器类的 DatabaseSeeder类,但是,你也可以使用 --class选项来指定你想要运行的独立的填充器类:

php artisan db:seedphp artisan db:seed --class=UserTableSeeder
Copy after login

你还可以使用 migrate:refresh命令来填充数据库,该命令还可以回滚并重新运行迁移,这在需要完全重建数据库时很有用:

php artisan migrate:refresh --seed
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles