laravel 社区 使用ModelFactory 生产测试数据 artisan 建表

来源:互联网 发布:python 3程序开发指南 编辑:程序博客网 时间:2024/05/01 03:06

php artisan make:migration create_discussions_table –create=discussions

public function up()
{
Schema::create(‘discussions’, function (Blueprint table) {table->increments(‘id’);
table>string(title);table->text(‘body’);
table>integer(userid)>unsigned();table->integer(‘last_user_id’)->unsigned();
table>foreign(userid)>references(id)>on(users)>onDelete(cascade);table->timestamps();
});
}

public function up()
{
Schema::create(‘users’, function (Blueprint table) {table->increments(‘id’);
table>string(name);table->string(‘avatar’); //添加头像
table>string(email)>unique();table->string(‘password’,60);
table>rememberToken();table->timestamps();
});
}

迁移表
php artisan migtate

在 User.php
protected $fillable = [‘name’, ‘email’, ‘password’,’avatar’];

在Discussion.php
protected $fillable = [‘title’, ‘body’, ‘user_id’,’last_user_id’];

在Model Factories

/*
|————————————————————————–

Model Factories Here you may define all of your model factories. Model factories give you a convenient way to create models for testing and seeding your database. Just tell the factory how a default model should look.

*/

factory>define(App\User::class,function(Faker\Generatorfaker) {
return [
‘name’ => faker>name,email=>faker->email,
‘avatar’ => $faker->imageUrl(256,256),
‘password’ => str_random(10),
‘remember_token’ => str_random(10),
];
});

通过使用 Laravel artisan 内建的 php artisan tinker , 我们可以很方便的看到数据库中的数据并且执行各种想要的操作。

创建30个user
D:\xampp\htdocs\laravelB\laravel>php artisan tinker
Psy Shell v0.7.2 (PHP 5.6.15 鈥?cli) by Justin Hileman

namespace App;
=> null
factory(User::class,30)->create();
得到等等 => Illuminate\Database\Eloquent\Collection {#699
all: [
App\User {#708
name: “Mrs. Cathy Gibson II”,
email: “gina.monahan@hotmail.com”,
avatar: “http://lorempixel.com/256/256/?79243“,
updated_at: “2016-08-07 13:08:29”,
created_at: “2016-08-07 13:08:29”,
id: 1,
},
App\User {#707
name: “Angela Wilderman”,
email: “rhane@huel.biz”,
avatar: “http://lorempixel.com/256/256/?12201“,
updated_at: “2016-08-07 13:08:29”,
created_at: “2016-08-07 13:08:29”,
id: 2,
},

在Model Factories
factory>define(App\Discussion::class,function(Faker\Generatorfaker) {
$user_ids = \App\User::lists(‘id’)->toArray(); /获得user_id 并转为 array/
return [
‘title’ => faker>sentence,body=>faker->paragraph,
‘user_id’ => faker>randomElement(user_ids),
‘last_user_id’ => faker>randomElement(user_ids),
];
});

0 0
原创粉丝点击