1
我想使用laravel種子創建測試數據。我可以種一張桌子。這裏是:Laravel使用工廠進行一對一的關係
ModelFactory.php:
/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\User::class, function (Faker\Generator $faker) {
static $password;
return [
'email' => $faker->unique()->safeEmail,
'password' => $password ?: $password = bcrypt('secret'),
'remember_token' => str_random(10),
'type' => '0'
];
});
UsersTableSeeder.php:
<?php
use Illuminate\Database\Seeder;
class UsersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run() {
factory(App\User::class, 50)->create()->each(function ($u) {
$u->posts()->save(factory(App\Post::class)->make());
});
}
}
我有兩個表它們是用戶和user_information。他們有一對一的關係。我想給用戶播種user_information。但我不知道,我該怎麼辦......
我的模型關係功能單元:
user.php的
public function userInformation() {
return $this->hasOne('App\UserInformation', 'user_id', 'id');
}
UserInformation.php
public function users() {
return $this->belongsTo('App\User', 'user_id', 'id');
}
Laravel版本是5.3我跟着這些文檔:
https://laravel.com/docs/5.3/seeding
https://laravel.com/docs/5.3/database-testing#writing-factories