Laravel5.1学习笔记18 数据库4 数据填充

Introduction

Laravel includes a simple method of seeding your database with test data using seed classes. All seed classes are stored in database/seeds. Seed classes may have any name you wish, but probably should follow some sensible convention, such as UserTableSeeder, etc. By default, a DatabaseSeeder class is defined for you. From this class, you may use the call method to run other seed classes, allowing you to control the seeding order.

Writing Seeders

To generate a seeder, you may issue the make:seeder Artisan command. All seeders generated by the framework will be placed in the database/seeders directory:

php artisan make:seeder UserTableSeeder

A seeder class only contains one method by default: run. This method is called when the db:seed Artisan commandis executed. Within the run method, you may insert data into your database however you wish. You may use thequery builder to manually insert data or you may use Eloquent model factories.

As an example, let‘s modify the DatabaseSeeder class which is included with a default installation of Laravel. Let‘s add a database insert statement to the run method:

<?php

use DB;
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table(‘users‘)->insert([
            ‘name‘ => str_random(10),
            ‘email‘ => str_random(10).‘@gmail.com‘,
            ‘password‘ => bcrypt(‘secret‘),
        ]);
    }
}

Using Model Factories

Of course, manually specifying the attributes for each model seed is cumbersome. Instead, you can use model factories to conveniently generate large amounts of database records. First, review the model factory documentation to learn how to define your factories. Once you have defined your factories, you may use the factoryhelper function to insert records into your database.

For example, let‘s create 50 users and attach a relationship to each user:

/**
 * Run the database seeds.
 *
 * @return void
 */
public function run()
{
    factory(‘App\User‘, 50)->create()->each(function($u) {
        $u->posts()->save(factory(‘App\Post‘)->make());
    });
}

Calling Additional Seeders

Within the DatabaseSeeder class, you may use the call method to execute additional seed classes. Using the callmethod allows you to break up your database seeding into multiple files so that no single seeder class becomes overwhelmingly large. Simply pass the name of the seeder class you wish to run:

/**
 * Run the database seeds.
 *
 * @return void
 */
public function run()
{
    Model::unguard();

    $this->call(‘UserTableSeeder‘);
    $this->call(‘PostsTableSeeder‘);
    $this->call(‘CommentsTableSeeder‘);
}

Running Seeders

Once you have written your seeder classes, you may use the db:seed Artisan command to seed your database. By default, the db:seed command runs the DatabaseSeeder class, which may be used to call other seed classes. However, you may use the --class option to specify a specific seeder class to run individually:

php artisan db:seed

php artisan db:seed --class=UserTableSeeder

You may also seed your database using the migrate:refresh command, which will also rollback and re-run all of your migrations. This command is useful for completely re-building your database:

php artisan migrate:refresh --seed
时间: 2024-10-29 19:08:21

Laravel5.1学习笔记18 数据库4 数据填充的相关文章

Laravel5.1学习笔记17 数据库3 数据迁移

Introduction Generating Migrations Migration Structure Running Migrations Rolling Back Migrations Writing Migrations Creating Tables Renaming / Dropping Tables Creating Columns Modifying Columns Dropping Columns Creating Indexes Dropping Indexes Fore

Laravel5.1学习笔记15 数据库1 数据库使用入门

Introduction Running Raw SQL Queries Listening For Query Events Database Transactions Using Multiple Database Connections Introduction Laravel makes connecting with databases and running queries extremely simple across a variety of database back-ends

Laravel5.1学习笔记16 数据库2 查询构造器

Introduction Retrieving Results Aggregates Selects Joins Unions Where Clauses Advanced Where Clauses Ordering, Grouping, Limit, & Offset Inserts Updates Deletes Pessimistic Locking Introduction The database query builder provides a convenient, fluent

springmvc学习笔记(18)-json数据交互

springmvc学习笔记(18)-json数据交互 springmvc学习笔记18-json数据交互 springmvc进行json交互 环境准备 添加json转换的依赖 配置json转换器 json交互测试 输入json串输出是json串 输入keyvalue输出是json串 本文主要介绍如何在springmvc中进行json数据的交互,先是环境准备和配置,然后分别展示了"输入json串,输出是json串"和"输入key/value,输出是json串"两种情况下

Oracle 学习笔记 18 -- 存储函数和存储过程(PL/SQL子程序)

PL/SQL子程序 包括函数和过程.这里的函数指的是用户自己定义的函数,和系统函数是不同的.子程序一般是完成特定功能的PL/SQL程序块,并且具有一定的通用性,可以被不同的应用程序多次调用.Oracle提供可以把PL/SQL程序存储在数据库中,并可以再任何地方来运行它.这样就叫做存储过程或者是函数.过程和函数的唯一区别就是函数总是向调用者返回数据,而过程则不返回数据. 函数 如果用户要经常执行某些操作,并且需要返回特定的数据,那么就可以将这些操作构造成一个函数. 可以使用SQL语句定义函数. 基

python基础教程_学习笔记18:标准库:一些最爱——shelve

标准库:一些最爱 shelve Shelve唯一有趣的函数是open.在调用它的时候(使用文件名作为参数),它会返回一个Shelf对象,可以用它来存储内容.只需要把它当作普通的字典(但是键一定要作为字符串)来操作即可,在完成工作之后,调用它的close方法. 意识到shelve.open函数返回的对象并不是普通的映射是很重要的. >>> import shelve >>> s=shelve.open('a.txt') >>> s['x']=['a','

Symfony2学习笔记之数据库操作

数据库和Doctrine让我们来面对这个对于任何应用程序来说最为普遍最具挑战性的任务,从数据库中读取和持久化数据信息.幸运的是,Symfony和Doctrine进行了集成,Doctrine类库全部目标就是给你一个强大的工具,让你的工作更加容易. Doctrine是完全解耦与Symfony的,所以并不一定要使用它. 一个简单例子:一个产品,我们首先来配置数据库,创建一个Product对象,持久化它到数据库并把它读回来. 首先我们需要创建一个bundle: $php app/console gene

Android学习笔记18:自定义Seekbar拖动条式样

Android学习笔记18:自定义Seekbar拖动条式样

Python学习笔记_Chapter 6定制数据对象

1. 有用的BIF a. 判断字符串中是否包含子字符串 1 if s_a in s_b: b. pop() 描述:从指定的列表位置删除并返回一个数据项. 1 (sarah_name,sarah_dob)=l_rah.pop(0),l_rah.pop(0) 2 #pop(0)中0位置为list中第一个数据项 3 #第一次执行pop赋值给sarah_name c. strip() 输入的是字符串,返回的是列表 d.open 读文件时可以多种方式打开文件,取出的数据是不同的,可以是文本也可以是二进制.