我想为我的模型创建一个created_by字段,比如Product,它会自动更新,我正在使用FOSUserBundle和Doctrine2。将用户ID输入产品的推荐方法是什么?
我可以在产品型号中执行此操作吗?我不知道该怎么做,任何帮助都会很精彩。谢谢!
我想在模型中做类似的事情,但我不知道如何获取用户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;
}
答案 0 :(得分: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;
并且对于自动更新字段,您可能在lifecyclecallbacks之后: 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)
}