[ Laravel 5.2 文档 ] 数据库 -- 填充数据
1、简介
Laravel包含了一个简单方法来填充数据库——使用填充类和测试数据。所有的填充类都位于 database/seeds目录。填充类的类名完全由你自定义,但最好还是遵循一定的规则,比如可读性,例如 UserTableSeeder等等。安装完 Laravel 后,会默认提供一个 DatabaseSeeder类。从这个类中,你可以使用 call方法来运行其他填充类,从而允许你控制填充顺序。
2、编写填充器
要生成一个填充器,可以通过 Artisan 命令 make:seeder。所有框架生成的填充器都位于 database/seeders目录:
php artisan make:seeder UserTableSeeder
一个填充器类默认只包含一个方法: 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'), ]); }}
使用模型工厂
当然,手动指定每一个模型填充的属性是很笨重累赘的,取而代之的,我们可以使用模型工厂来方便的生成大量的数据库记录。首先,查看模型工厂文档来学习如何定义工厂,定义工厂后,可以使用帮助函数 factory来插入记录到数据库。
举个例子,让我们创建50个用户并添加关联关系到每个用户:
/** * 运行数据库填充 * * @return void */public function run(){ factory('App\User', 50)->create()->each(function($u) { $u->posts()->save(factory('App\Post')->make()); });}
调用额外的填充器
在 DatabaseSeeder类中,你可以使用 call方法执行额外的填充类,使用 call方法允许你将数据库填充分解成多个文件,这样单个填充器类就不会变得无比巨大,只需简单将你想要运行的填充器类名传递过去即可:
/*** 运行数据库填充** @return void*/public function run(){ Model::unguard(); $this->call(UserTableSeeder::class); $this->call(PostsTableSeeder::class); $this->call(CommentsTableSeeder::class); Model::reguard();}
3、运行填充器
编写好填充器类之后,可以使用 Artisan 命令 db:seed来填充数据库。默认情况下, db:seed命令运行可以用来运行其它填充器类的 DatabaseSeeder类,但是,你也可以使用 --class选项来指定你想要运行的独立的填充器类:
php artisan db:seedphp artisan db:seed --class=UserTableSeeder
你还可以使用 migrate:refresh命令来填充数据库,该命令还可以回滚并重新运行迁移,这在需要完全重建数据库时很有用:
php artisan migrate:refresh --seed
Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

In PHP, the difference between include, require, include_once, require_once is: 1) include generates a warning and continues to execute, 2) require generates a fatal error and stops execution, 3) include_once and require_once prevent repeated inclusions. The choice of these functions depends on the importance of the file and whether it is necessary to prevent duplicate inclusion. Rational use can improve the readability and maintainability of the code.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7
