一、数据迁移
1、使用 Artisan 命令make:migration来创建一个新的迁移:
php artisan make:migration create_users_table
// 可以使用 --path指定生成的目标路径
php artisan make:migration --path=app\providers create_users_table
// 还可以一次性创建Model和migration
// 下述命令会做两件事情:
// 在 app 目录下创建模型类 App\Post
// 创建用于创建 posts 表的迁移,该迁移文件位于 database/migrations 目录下。
php artisan make:model --migration Post
执行成功后会在database\migrations目录下生成如下格式的php文件
2016_05_05_060000_create_users_table.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{ // 创建表
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
迁移的顺序跟生成迁移文件的时间有关系。如果要修改表结构,比如说添加某个字段,需要在创建表之后执行,
比如说为users表添加软删除(也就是添加deleted_at字段)
php artisan make:migration update_users_table
在生成的php文件中添加如下代码
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class UpdateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function(Blueprint $table){
// 软删除
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function(){
$table->dropSoftDeletes();
});
}
}
二、数据填充
要生成一个填充器,可以通过 Artisan 命令make:seeder。所有框架生成的填充器都位于database/seeders目录:
php artisan make:seeder UsersTableSeeder
在生成的UsersTableSeeder.php中
<?php
use Illuminate\Database\Seeder;
class UserTableSeeder extends Seeder{
/**
* 运行数据库填充
*
* @return void
*/
public function run()
{
DB::table('users')->insert([
'name' => str_random(10),
'email' => str_random(10).'@gmail.com',
'password' => bcrypt('secret'),
]);
}
}
在DatabaseSeeder类中,你可以使用call方法执行额外的填充类,
<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{ // 取消批量插入限制
Model::unguard();
$this->call(UsersTableSeeder::class);
}
}
最后执行
php artisan db:seed
// 指定某个表的类名
// 指定类名后不需要在DatabaseSeeder.php中添加call方法
php artisan db:seed --class=UsersTableSeeder
3、通过factory模型仓库填充
在DatabaseSeeder类中,run方法中使用call方法执行相应的填充类
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$this->call(UsersTableSeeder::class);
$this->call(TagsTableSeeder::class);
$this->call(PostsTableSeeder::class);
}
}
在database\factories\ModelFactory.php中定义仓库模型
<?php $factory->define(App\User::class, function (Faker\Generator $faker) { return [ 'name' => $faker->name, 'email' => $faker->safeEmail, 'password' => bcrypt(str_random(10)), 'remember_token' => str_random(10), ]; }); $factory->define(App\Post::class, function($faker) { $images = ['about-bg.jpg', 'contact-bg.jpg', 'home-bg.jpg', 'post-bg.jpg']; $title = $faker->sentence(mt_rand(3, 10)); return [ 'title' => $title, 'subtitle' => str_limit($faker->sentence(mt_rand(10, 20)), 252), 'page_image' => $images[mt_rand(0, 3)], 'content_raw' => join("\n\n", $faker->paragraphs(mt_rand(3, 6))), 'publish_at' => $faker->dateTimeBetween('-1 month', '+3 days'), 'meta_description' => "Meta for $title", 'is_draft' => false, ]; }); $factory->define(App\Tag::class, function($faker) { $images = ['about-bg.jpg', 'contact-bg.jpg', 'home-bg.jpg', 'post-bg.jpg']; $word = $faker->word; return [ 'tag' => $word, 'title' => ucfirst($word), 'subtitle' => $faker->sentence, 'page_image' => $images[mt_rand(0, 3)], 'meta_description' => "Meta for $word", 'reverse_direction' => false, ]; });
生成model
// 以Post举例
php artisan make:model Post
生成填充类
php artisan make:seeder PostsTableSeeder
在PostsTableSeeder.php中调用
<?php use App\Post; use App\Tag; use Illuminate\Database\Seeder; class PostsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Post::truncate(); $tags = Tag::lists('tag')->all(); DB::table('post_tag_pivot')->truncate(); factory(Post::class, 20)->create()->each(function($post) use($tags) { if (mt_rand(1, 100) <= 30) { return; } shuffle($tags); $postTags = [$tags[0]]; if (mt_rand(1, 100) <= 30) { $postTags[] = $tags[1]; } $post->syncTags($postTags); }); } }
<?php
use App\Tag;
use Illuminate\Database\Seeder;
class TagsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Tag::truncate();
factory(Tag::class, 5)->create();
}
}
如果想在执行填充入库前对数据模型中的某个属性进行相关的操作,可以在相应的模型中定义set(字段)Attribute方法
比如说对posts表中的字段content_raw进行操作,同时还可以在该方法中操作其他字段,如content_html字段
public function setContentRawAttribute($value) {
$markdown = new Markdowner();
$this->attributes['content_raw'] = $value;
$this->attributes['content_html'] = $markdown->toHTML($value);
}
迁移并填充数据
php artisan migrate --seed