php Symfony角色未在数据库中保存为数组

zc0qhyus  于 2022-11-28  发布在  PHP
关注(0)|答案(1)|浏览(94)

我的用户实体的角色在数据库中保存不好。
我有一个基本的问题,但我没有找到答案,所以我在这里问自己。当我创建一个用户时,他注册了角色ROLE_USER。但在我的数据库中,他保存为:0:{}。您知道我可以做什么来默认将其存储为[]吗?

zysjyyx4

zysjyyx41#

好了这里是我的用户实体:

<?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(),
]);

}
对不起,代码格式不正确,我复制过去,它来的方式。

相关问题