Symfony 4 SQLSTATE [23000]:记录器到数据库操作的重复输入问题

Symfony4 QLSTATE[23000]: Duplicate entry problem with logger to database action

我有一个应用程序,我必须在其中记录每个用户操作,URL 他访问了什么,他的操作是否成功。因此,为此我让监听器检查每个访问过的 URL 和 LogFactory,如下所示:

class UserLogFactory
{
    private $container;
    private $entityManager;
    private $platform;
    private $logRepository;
    private $request;
    private $userLogger;

public function __construct(ContainerInterface $container,
                            EntityManagerInterface $entityManager,
                            UserPlatformChecker $platform,
                            UserLogTypeRepository $logRepository,
                            RequestStack $request,
                            LoggerInterface $userLogger
)
{
    $this->container = $container;
    $this->entityManager = $entityManager;
    $this->platform = $platform;
    $this->logRepository = $logRepository;
    $this->request = $request;
    $this->userLogger = $userLogger;
}

public function userLogFactory($logType, $logText)
{
    $request = $this->request->getCurrentRequest();
    $token = $this->container->get('security.token_storage')->getToken();

    if ($token === null || !($token->getUser() instanceof User)) {
        return;
    }

    $user = $token->getUser();
    $platform = $this->platform->getPlatform($request);
    $ip = $request->getClientIp();
    $date = new \DateTime('now');
    $url = $request->getUri();

    $log = new UserLog();
    $log->setUser($user);
    $log->setType($logType);
    $log->setPlatform($platform);
    $log->setIp($ip);
    $log->setDate($date);
    $log->setUrl($url);
    $log->setLogText($logText);

    $this->entityManager->persist($log);
    $this->entityManager->flush();
}
}

我在我的控制器中记录操作,例如,当一些用户管理员试图编辑另一个用户时,我做了这样的事情:

public function editUser(User $user, Request $request, UserPasswordEncoderInterface $passwordEncoder, EntityManagerInterface $entityManager)
{
    // First form for edit User //
    $userForm = $this->createForm(EditUserType::class, $user);
    $userForm->handleRequest($request);

    if ($userForm->isSubmitted() && $userForm->isValid()) {
        $entityManager->flush();
        $this->addFlash('notice', 'Profile has been edited');

        $logType = $this->logRepository->find(UserLogType::SUCCESS_ACTION);
        $this->userLogFactory->userLogFactory($logType, 'User edited user profile.');

        return $this->redirectToRoute('user_list');

    }
    elseif ($userForm->isSubmitted() && !$userForm->isValid()) {
        $logType = $this->logRepository->find(UserLogType::FAILED_ACTION);
        $this->userLogFactory->userLogFactory($logType, 'User has failed to edit user profile.');
    }

我的问题在哪里,UserAdmin 尝试更改数据库中已经存在的用户登录我有 SQL 错误:

An exception occurred while executing 'UPDATE user SET login = ? WHERE id = ?' with params ["aaa", 2]:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'aaa' for key 'UNIQ_8D93D649AA08CB10'

我不知道我应该更改什么才能获得正常的表单验证消息,例如。使用该登录名的用户已存在。

我知道 UserLogFactory 有问题,因为没有它一切正常,但我无法确定原因。

编辑。这是我的用户实体:

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 * @UniqueEntity("login")
 */
class User implements UserInterface
{
public const ROLE_USER = 'ROLE_USER';

/**
 * @ORM\Id()
 * @ORM\GeneratedValue()
 * @ORM\Column(type="integer")
 */
private $id;

/**
 * @ORM\Column(type="string", length=10, unique=true)
 */
private $login;

/**
 * @ORM\Column(type="string", length=255)
 */
private $password;

/**
 * @ORM\ManyToMany(targetEntity="App\Entity\UserPermissionList")
 * @ORM\JoinTable(name="user_permisions")
 */
private $permissions;

ETC.    

你有

@UniqueEntity("login")

这意味着您不能在登录列中有 2 行具有相同的值。在这种情况下

An exception occurred while executing 'UPDATE user SET login = ? WHERE id = ?' with params ["aaa", 2]: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'aaa' for key 'UNIQ_8D93D649AA08CB10'

这意味着您在用户 table 中有另一行,登录列中已经有 'aaa' 值

编辑:

添加这个:

@UniqueEntity(fields="login", message="This login already exist")

编辑 2 好的,我想出了解决问题的方法,我只是像教程中那样使用 Form Model Class