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

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\Generator faker) {
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\Generator faker) {
$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),
];
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值