1

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

我可以在 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;
    }
4

1 回答 1

3

要将用户与您想要关联两个实体的产品相关联: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)
}
于 2012-06-12T07:47:54.933 回答