我试图像这样尝试种子数据库:
factory(App\User::class, 1)
->create()
->each(function($u) {
$role = factory(App\Role::class)->create();
$u->role()->save( $role );
});
这些是我的模型工厂:
$factory->define(App\User::class, function (Faker\Generator $faker) {
return [
'name' => 'Jakub Kohout',
'email' => 'test@gmail.com',
'password' => bcrypt('Uchiha'),
'role_id' => 1
];
});
$factory->define(App\Role::class, function (Faker\Generator $faker) {
return [
'role_name' => 'Admin',
];
});
但我收到了这个错误:
Undefined property: Illuminate\Database\Eloquent\Builder::$orders
我做错了什么?
答案 0 :(得分:4)
可悲的是,每个功能都不适用于单个元素。您必须创建多个模型才能使用每个函数:
factory(App\User::class, 2)->create()->each(function($u) {
$role = factory(App\Role::class)->create();
$u->role()->save( $role );
});
如果只创建了一个元素,则直接返回实例而不是集合。
这适用于您的情况:
$user = factory(App\User::class)->create();
$role = factory(App\Role::class)->create();
$user->role()->save( $role );