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

Laravel 6 Factory, can't access relationship methods after using state

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

$factory->define(User::class, function (Faker $faker) {
  return [
    'email' => $faker->unique()->safeEmail,
    'email_verified_at' => now(),
    'password' => 'yIXUNpkjO0rOQ5byMi.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

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

要为每个用户分配 'Admin' 角色,您必须迭代他们

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

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