doudao1369 2012-12-06 10:34
浏览 4
已采纳

在实体内创建和持久化新实体实例

I have an entity that needs to return an instance of another entity - the stored record or a new one if one has not been stored.

<?php

/**
 * @Entity
 */
class User {
    /**
     * @OneToOne(targetEntity="Basket")
     * @JoinColumn(nullable=true)
     */
    protected $activeBasket;

    public function getActiveBasket() {
        if (!isset($this->activeBasket)) {
            $this->activeBasket = new Basket($this);
            // $em->persist($this->activeBasket);
            // $em->flush();
        }
        return $this->activeBasket;
    }
}

My problem is that I don't have an EntityManager to use to persist this new Basket (and obviously don't want one in the Model). I'm not sure as to the best way to do this. I do want to be able to call $user->getActiveBasket() and retrieve a basket, whether it's previously created or a new one.

It feels like this should be a common problem, or that there's a better way to structure this (I'm hoping there's a way to hook one in in an EntityRepository or something). How can I do this?

  • 写回答

1条回答 默认 最新

  • douchibu7040 2012-12-06 11:13
    关注

    I wouldn't return a new Basket() when it is null or not set. The model (entity) should only serve for setting and getting its properties.

    The logic when $user->getActiveBasket() returned null should be elsewhere - in controller or in entity's reporitory object...

    So I would move public function getActiveBasket() { ... } into just public function getActiveBasket() { return $this->activeBasket; } and somewhere in the controller I would do:

    $if(!$user->getActiveBasket()) {
        $user->setActiveBasket(new Basket($user));
        $this->_em->persist($user);
        $this->_em->flush();
    }
    // now do something with that activeBasket...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥15 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)