多对多为何获取不到插入的关联数据?
class Register extends Command
{
use DispatchesJobs, DisplayUserTable;
/**
* The command name.
*
* @var string
*/
protected $name = 'users:new';
/**
* The command description.
*
* @var string
*/
protected $description = 'Create a new user.';
/**
* Handle the command.
*
* @param UserRepositoryInterface $users
* @param RoleRepositoryInterface $roles
*/
public function handle(UserRepositoryInterface $users, RoleRepositoryInterface $roles)
{
$data = collect();
$data->put('visitant_id', 1);
$data->put('visitant_value', 10);
nikename:
$data->put('nikename', $this->ask('Enter the desired nikename.', null));
if ( $users->findByNikename($data->get('nikename')) instanceof UserInterface )
{
$this->error('The nickname you entered already exists.');
goto nikename;
}
username:
$data->put('username', $this->ask('Enter the desired username.', Str::random()));
if ( $users->findByUsername($data->get('username')) instanceof UserInterface )
{
$this->error('The username you entered already exists.');
goto username;
}
email:
$data->put('email', $this->ask('Enter the desired email.', Str::random(6) . '@ofcold.com'));
if ( ! filter_var($data->get('email'), FILTER_VALIDATE_EMAIL) )
{
$this->error('Please enter correct email.');
goto email;
}
if ( $users->findByEmail($data->get('email')) instanceof UserInterface )
{
$this->error('The email you entered already exists.');
goto email;
}
mobile_phone:
$data->put('mobile_phone', $this->ask('Enter the desired mobile phone.', null));
if ( ! preg_match('/^1(?:3[0-9]|4[5-9]|5[0-9]|66|7[014-8]|8[0-9]|9[89]|99)\d{8}$/', $data->get('mobile_phone')) )
{
$this->error('Please enter correct mobil phone.');
goto mobile_phone;
}
if ( $users->findByMobilePhone($data->get('mobile_phone')) instanceof UserInterface )
{
$this->error('The mobile phone you entered already exists.');
goto mobile_phone;
}
$data->put('password', $this->ask('Enter the desired password.', Str::random(15)));
$data->put('enabled', $this->ask('Do you want to enable this user?', true));
$rolesCollection = $roles->all()->map(function($role) {
return $role->getSlug();
})->toArray();
role:
$role = $this->askWithCompletion(
'What role do you want to use for this user? [' . implode(',', $rolesCollection) . ']',
$rolesCollection,
'user'
);
if ( ! in_array($role, $rolesCollection, true) )
{
$this->error('Please select the correct user role.');
goto role;
}
$user = $users->create($data->toArray());
if ( $role = $this->dispatch(new GetRole($role)) )
{
$user->attachRole($role);
}
$this->alert('You have successfully created a user.');
// 这里获取刚插入用户的数据,可是拿不到角色的数据。
$this->table($this->headers, [$this->getUserRow($user)]);
}
}
推荐文章: