【问题标题】:Saving current user id in repository在存储库中保存当前用户 ID
【发布时间】:2019-03-27 18:36:30
【问题描述】:

我尝试在 UserService 实体中保存用户字段的初始值。原因是,我在 EasyAdminBundle 中使用了这个实体,当我构建表单时,我想为 user_id 设置一个默认值(ManyToOne to User 实体)。

  • 在构造函数中初始化实体管理器,
  • 我重写了保存方法。
  • 我从安全会话上下文中获取用户并设置为用户服务对象、持久化和刷新。

...但我在保存过程中仍然看不到变化。

class UserServiceRepository extends ServiceEntityRepository
{

protected $_em;

public function __construct(RegistryInterface $registry)
{

    $this->_em = $this->entityManager;

    parent::__construct($registry, UserService::class);
}

// I override save method:
public function save(UserService $userService)
{
    // Get current user from security:
    $user = $this->get('security.token_storage')->getToken()->getUser();
    // set to useService...
    $userService->setUser($user);

        // and persist & flush:
        $this->_em->persist($userService);
        $this->_em->flush();


}

【问题讨论】:

    标签: symfony doctrine-orm symfony4 symfony2-easyadmin easyadmin


    【解决方案1】:
    // I override save method:
    

    您正在覆盖父级中不存在的方法,ServiceEntityRepository 和 EntityRepository 中都没有保存方法。那么您所做的工作的重点是什么以及为什么要在服务存储库中设置默认 user_id?

    更新:

    services:
        my.listener:
            class: UserServiceListener
            arguments:
                - "@security.token_storage"
            tags:
                - { name: doctrine.event_listener, event: prePersist }
    

    听众:

    class UserServiceListener
    {
        private $token_storage;
    
        public function __construct(TokenStorageInterface $token_storage)
        {
            $this->token_storage = $token_storage;
        }
    
        public function prePersist(LifeCycleEventArgs $args)
        {
            $entity = $args->getEntity();
    
            if (!$entity instanceof UserService) {
               return;
            }
    
            $entity->setUser($this->token_storage->getToken()->getUser());
        }
    }
    

    【讨论】:

    • 谢谢。我使用easyadminbundle...我为userservice定义了一个表单...我需要在user_service中将当前用户ID设置为默认值
    • UserService 对象是学说实体?令牌存储的主要思想是按令牌检索用户并为其恢复会话,但是您想保留相关对象,对吗?因此,每次您发起请求时 - 都会对您的实体进行写入操作
    • 每次保存 user_service 时,我希望 user_service.user_id 等于登录用户的活动用户 ID。
    • 好的,知道了。看上面的代码,你应该为你的 UserService 实体创建一个带有 prePersist 方法的学说事件监听器
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-16
    • 2016-10-27
    • 2020-12-13
    • 2020-08-22
    • 1970-01-01
    相关资源
    最近更新 更多