Laravel 6 Factory,使用状态后无法访问关系方法

时间:2019-11-12 09:21:05

标签: laravel unit-testing factory

假设我有一个用户工厂来创建用户,对于特定用户我想添加更多信息,为此,我已经在工厂内部定义了状态,但是如果使用状态,则无法在用户之后调用用户的相关方法创建假设我应该使用assignRole($role)向用户分配角色。 以下是我的UserFactory.php

$factory->define(User::class, function (Faker $faker) {
  return [
    'email' => $faker->unique()->safeEmail,
    'email_verified_at' => now(),
    'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
    'remember_token' => Str::random(10),
    'first_name' => $faker->name,
    'last_name' => $faker->lastName,
    'phone' => $faker->phoneNumber,
    'password' => bcrypt('12345678'),
 ];
});

$factory->state(User::class, 'Admin', function (Faker $faker) {
$country = factory(Country::class)->create();
$province = factory(Province::class)->create();
static $afghanistanId = 1;
$admin= [
    'about' => $faker->sentence($nbWords = 20, $variableNbWords = true),
    'address' => $faker->address,
];
if($country->id  == $afghanistanId) {
    $admin['province_id'] = $province->id;
} else {
    $admin['city'] = $faker->city;
}
return $admin;
});

现在,如果我像波纹管一样使用这个工厂:

$user = factory(User::class, $count)->state('Admin')->create();

$user->assignRole('Admin');

以下显示此错误:

BadMethodCallException: Method Illuminate\Database\Eloquent\Collection::assignRole does not exist

1 个答案:

答案 0 :(得分:1)

通过将$count传递到工厂方法$user = factory(User::class, $count)...->create();,您将创建多个用户,并且返回的是Collection,就像您的错误所言。

要将“管理员”角色分配给每个用户,您必须对其进行迭代

$users = factory(User::class, $count)->state('Admin')->create();

foreach($users as $user)
    $user->assignRole('Admin');