【问题标题】:Automatically updating created_by in the model自动更新模型中的 created_by
【发布时间】:2012-06-12 04:19:09
【问题描述】:

我想为我的模型创建一个 created_by 字段,比如 Product,它会自动更新,我正在使用 FOSUserBundle 和 Doctrine2。将 User id 输入到 Product 中的推荐方式是什么?

我可以在 Product 模型中执行此操作吗?我不知道该怎么做,任何帮助都会很棒。谢谢!

我想在模型中做这样的事情,但我不知道如何获取用户ID。

   /**
     * Set updatedBy
     *
     * @ORM\PrePersist
     * @ORM\PreUpdate
     * @param integer $updatedBy
     */
    public function setUpdatedBy($updatedBy=null)
    {
        if (is_null($updatedBy)) {
            $updatedBy = $user->id;
        }
        $this->updatedBy = $updatedBy;
    }

【问题讨论】:

    标签: symfony doctrine-orm fosuserbundle


    【解决方案1】:

    要将用户与您想要关联两个实体的产品相关联: http://symfony.com/doc/current/book/doctrine.html#entity-relationships-associations

    /**
     * @ORM\ManyToOne(targetEntity="User", inversedBy="products")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     * You may need to use the full namespace above instead of just User if the
     * User entity is not in the same bundle e.g FOS\UserBundle\Entity\User
     * the example is just a guess of the top of my head for the fos namespace though
     */
    protected $user;
    

    对于自动更新字段,您可能在生命周期回调之后: http://symfony.com/doc/current/book/doctrine.html#lifecycle-callbacks

    /**
     * @ORM\Entity()
     * @ORM\HasLifecycleCallbacks()
     */
    class Product
    {
        /**
         * @ORM\PreUpdate
         */
        public function setCreatedValue()
        {
            $this->created = new \DateTime();
        }
    }
    

    编辑

    这个讨论讨论了在实体中获取容器,在这种情况下,如果您打算将当前用户与他们编辑的产品相关联,您可以获取 security.context 并从中找到用户 ID: https://groups.google.com/forum/?fromgroups#!topic/symfony2/6scSB0Kgds0

    //once you have the container you can get the session
    $user= $this->container->get('security.context')->getToken()->getUser();
    $updated_at = $user->getId();
    

    也许这就是您所追求的,但不确定将容器放在实体中是否是个好主意,您能否仅在产品控制器的更新操作中将用户设置在产品上:

    public function updateAction(){
       //....
       $user= $this->get('security.context')->getToken()->getUser();
       $product->setUser($user)
    }
    

    【讨论】:

    • 我想知道如何从 setCreatedBy() 等函数中获取用户 ID。我可以通过模型来做吗?
    • 我猜你可以在函数内部return $this->getUser()->getId()。您能否给出问题中的使用示例以及您希望它如何工作?
    • 我编辑了我的问题以使其更清晰。我想从模型中获取登录用户的 ID。这可能吗?
    • 我无法在实体中获取 $this->container。我已经在我的 Product 实体中扩展了 ContainerAware。我要在 services.yml 中添加一些东西吗?对此有何建议?
    • 您还需要使用事件订阅者groups.google.com/forum/?fromgroups#!topic/symfony2/WWIc8N7KZrg 这有点超出我的能力。订阅者在这里解释:symfony.com/doc/current/cookbook/doctrine/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-10
    • 2021-12-20
    • 2012-06-22
    • 2012-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多