Роли моей пользовательской сущности плохо сохраняются в базе данных.
У меня есть основной вопрос, но я не нашел решения, поэтому задаю его здесь. Когда я создаю пользователя, он регистрируется с ролью ROLE_USER. Но в моей базе он сохраняется как:0:{} У вас есть идея, что я могу сделать, чтобы сохранить их как [] по умолчанию.
Хорошо, вот мой пользовательский объект:
<?php
namespace App\Entity;
use App\Repository\UserRepository;
use DateTime;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
#[ORM\Entity(repositoryClass: UserRepository::class)]
#[ORM\Table(name: '`user`', options:["collate"=>"utf8mb4_unicode_ci", "charset"=>"utf8mb4"])]
#[UniqueEntity(fields: ['mail'], message: 'There is already an account with this mail.')]
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(type: Types::ARRAY, nullable: true)]
private array $roles = [];
#[ORM\Column(length: 255)]
private ?string $username = null;
#[ORM\Column(length: 255)]
private ?string $password = null;
#[ORM\Column(length: 255)]
private ?string $group_role = null;
#[ORM\Column(length: 255)]
private ?string $mail = null;
#[ORM\Column(length: 255)]
private ?string $firstname = null;
#[ORM\Column(length: 255)]
private ?string $lastname = null;
#[ORM\Column(type: Types::DATETIME_MUTABLE, options: ['default' => 'CURRENT_TIMESTAMP'])]
private ?\DateTime $create_datetime = null;
#[ORM\Column(length: 255)]
private ?string $notif_rule = null;
#[ORM\OneToMany(mappedBy: 'his_user', targetEntity: Logs::class, orphanRemoval: true)]
private Collection $logs;
#[ORM\OneToMany(mappedBy: 'his_user', targetEntity: Session::class)]
private Collection $sessions;
#[ORM\OneToMany(mappedBy: 'his_user', targetEntity: Access::class, orphanRemoval: true)]
private Collection $accesses;
public function __construct()
{
$this->logs = new ArrayCollection();
$this->sessions = new ArrayCollection();
$this->accesses = new ArrayCollection();
$this->create_datetime = new \DateTime( );
}
public function getId(): ?int
{
return $this->id;
}
/**
* @see UserInterface
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
public function getUsername(): ?string
{
return $this->username;
}
public function setUsername(string $username): self
{
$this->username = $username;
return $this;
}
public function getPassword(): ?string
{
return $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
public function getGroupRole(): ?string
{
return $this->group_role;
}
public function setGroupRole(string $group_role): self
{
$this->group_role = $group_role;
return $this;
}
public function getMail(): ?string
{
return $this->mail;
}
public function setMail(string $mail): self
{
$this->mail = $mail;
return $this;
}
public function getFirstname(): ?string
{
return $this->firstname;
}
public function setFirstname(string $firstname): self
{
$this->firstname = $firstname;
return $this;
}
public function getLastname(): ?string
{
return $this->lastname;
}
public function setLastname(string $lastname): self
{
$this->lastname = $lastname;
return $this;
}
public function getCreateDatetime(): ?\DateTimeInterface
{
return $this->create_datetime;
}
public function setCreateDatetime(\DateTimeInterface $create_datetime): self
{
$this->create_datetime = $create_datetime;
return $this;
}
public function getNotifRule(): ?string
{
return $this->notif_rule;
}
public function setNotifRule(string $notif_rule): self
{
$this->notif_rule = $notif_rule;
return $this;
}
/**
* @return Collection<int, Logs>
*/
public function getLogs(): Collection
{
return $this->logs;
}
public function addLog(Logs $log): self
{
if (!$this->logs->contains($log)) {
$this->logs->add($log);
$log->setHisUser($this);
}
return $this;
}
public function removeLog(Logs $log): self
{
if ($this->logs->removeElement($log)) {
// set the owning side to null (unless already changed)
if ($log->getHisUser() === $this) {
$log->setHisUser(null);
}
}
return $this;
}
/**
* @return Collection<int, Session>
*/
public function getSessions(): Collection
{
return $this->sessions;
}
public function addSession(Session $session): self
{
if (!$this->sessions->contains($session)) {
$this->sessions->add($session);
$session->setHisUser($this);
}
return $this;
}
public function removeSession(Session $session): self
{
if ($this->sessions->removeElement($session)) {
// set the owning side to null (unless already changed)
if ($session->getHisUser() === $this) {
$session->setHisUser(null);
}
}
return $this;
}
/**
* @return Collection<int, Access>
*/
public function getAccesses(): Collection
{
return $this->accesses;
}
public function addAccess(Access $access): self
{
if (!$this->accesses->contains($access)) {
$this->accesses->add($access);
$access->setHisUser($this);
}
return $this;
}
public function removeAccess(Access $access): self
{
if ($this->accesses->removeElement($access)) {
// set the owning side to null (unless already changed)
if ($access->getHisUser() === $this) {
$access->setHisUser(null);
}
}
return $this;
}
/**
* A visual identifier that represents this user
*
* @see UserInterface
*/
public function getUserIdentifier(): string
{
return (string) $this->mail;
}
/**
* @see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
}
И вот мой маршрут:
#[Route('/register', name: 'app_register')]
public function register(Request $request, UserPasswordHasherInterface $userPasswordHasher, UserAuthenticatorInterface $userAuthenticator, UserAuthenticator $authenticator, EntityManagerInterface $entityManager): Response
{
$user = new User();
$form = $this->createForm(RegistrationFormType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// encode the plain password
$user->setPassword(
$userPasswordHasher->hashPassword(
$user,
$form->get('plainPassword')->getData()
)
);
$entityManager->persist($user);
$entityManager->flush();
// do anything else you need here, like send an email
return $userAuthenticator->authenticateUser(
$user,
$authenticator,
$request
);
}
return $this->render('registration/register.html.twig', [
'registrationForm' => $form->createView(),
]);
}
Извините, код неправильно отформатирован, я скопировал его, и он пришел таким образом.
Но если я правильно вас понял, нет никаких проблем с тем, что это в моей базе данных? Будет ли он правильно распознан моим кодом? Если ответ да, то это решило мою проблему :)
Да, здесь у вас будет просто имя пользователя, которое уже существует, записанное во вводе, и этот ввод будет неизменным, поэтому, когда форма будет отправлена, имя пользователя не будет изменено. Это делает его постоянным, и я думаю, это то, что вы хотите сделать.
Именно так массивы сохраняются в базе данных. Вы получаете какие-либо ошибки? Можете ли вы предоставить дополнительный контекст, такой как ваш пользовательский объект и класс создания пользователя.