【问题标题】:Doctrine 2 postPersist then save/update entityDoctrine 2 postPersist 然后保存/更新实体
【发布时间】:2014-09-10 00:04:25
【问题描述】:

我正在创建一个我想插入到我的许多 Doctrine 实体类中的特征。该特征基本上允许使用基于实体 id(主键)的 Hashids PHP 库创建 slug 属性。

我已经在 trait 中包含了所需的属性和 getter/setter 以及 postPersist() 方法,但我现在想知道如何从 postPersist() 中重新保存/更新/持久化该更改方法?

任何帮助或指导都会很棒。

SlugTrait

trait Slug
{
    /**
     * @ORM\Column(type="string")
     */
    private $slug;

    /**
     * @ORM\PostPersist
     */
    public function postPersist()
    {
        $this->slug = (new SlugCreator())->encode($this->id);

        // Save/persist this newly created slug...?
    }

    public function getSlug()
    {
        return $this->slug;
    }

    public function setSlug($slug)
    {
        $this->slug = $slug;
    }
}

【问题讨论】:

    标签: php doctrine-orm doctrine


    【解决方案1】:

    经过反复试验,我发现了如何保持更新/更改。当我使用 Laravel 时,我刚刚从 IoC 容器中解析了实体管理器,然后使用它来保存更新的 slug 字段,就像这样(您也可以手动新建实体管理器):

    trait Slug
    {
        /**
         * @ORM\Column(type="string")
         */
        protected $slug;
    
        /**
         * @ORM\PostPersist
         */
        public function postPersist()
        {
            $this->slug = (new SlugCreator())->encode($this->id);
    
            // Save/persist this newly created slug.
            // Note: We must add the top level class annotation
            // '@ORM\HasLifecycleCallbacks()' to any Entity that
            // uses this trait.
            $entityManager = App::make('Doctrine\ORM\EntityManagerInterface'); // or new up the em "new EntityManager(...);
            $entityManager->persist($this);
            $entityManager->flush();
        }
    
        public function getSlug()
        {
            return $this->slug;
        }
    
        public function setSlug($slug)
        {
            $this->slug = $slug;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-02-22
      • 1970-01-01
      • 1970-01-01
      • 2018-08-23
      • 1970-01-01
      • 2014-10-29
      • 1970-01-01
      • 2014-12-15
      • 2016-03-24
      相关资源
      最近更新 更多