【问题标题】:Doctrine 2.1 - entity inserting学说 2.1 - 实体插入
【发布时间】:2012-01-02 16:29:22
【问题描述】:

我对将实体插入数据库有疑问。我有两个模型:

class News {
    /**
     * @Column(type="string", length=100)
     * @var string
     */
    protected $title;

    /**
     * @ManyToOne(targetEntity="User", inversedBy="news")
     * @JoinColumn(referencedColumnName="id")
     */ 
    protected $author;

}

class User {
    /**
     * @Id @GeneratedValue @Column(type="integer")
     * @var integer
     */
    protected $id;

    /**
     * @OneToMany(targetEntity="News", mappedBy="author")
     */
    protected $news;

    public function __construct() {
        $this->news = new \Doctrine\Common\Collections\ArrayCollection;
    }

}

要添加新新闻,我必须同时包含 UserNews 类(如果它们位于单独的文件中,例如 UserModel.php 和 NewsModel.php)并编写代码:

$news = new News()
$news->setTitle('TEST title');
$news->setAuthor($database->find('User', 1));
$database->persist($news);

我的问题是:有没有什么方法可以在不包含User 类的情况下插入新闻?

【问题讨论】:

  • 你的意思是:如何在没有用户的情况下制作新闻?
  • 我的意思是,我只能给出用户的 ID 而不是整个用户对象。例如。比如$news->setAuthor(1);INSERT INTO News VALUES ('TEST title', 1);

标签: php doctrine doctrine-orm


【解决方案1】:

您不需要实际加载用户。

相反,您可以使用reference proxy

<?PHP
$news = new News()
$news->setTitle('TEST title');
$news->setAuthor($em->getReference('User',1));
$em->persist($news);

【讨论】:

  • 谢谢!再问你一个问题。有什么办法可以做这个参考,但是用其他列(不是 ID)?
  • 我不这么认为。您需要被引用实体的标识值。
  • 还有一个问题。这是getReference()find() 方法快吗?
【解决方案2】:

您可以做的另一件事(以更面向对象的方式思考)是在您的用户实体上添加一个名为 addNews($news) 的方法:

public function addNews($news) {
    // you should check if the news doesn't already exist here first
    $this->news->add($news);
    $news->setAuthor($this);
}

并将级联持久性添加到您的映射中:

/**
 * @OneToMany(targetEntity="News", mappedBy="author", cascade={"persist"})
 */
protected $news;

然后获取您的用户、添加新闻并合并更改:

$news = new News()
$news->setTitle('TEST title');    
$author = $database->find('User', 1);

$author->addNews($news);

//merge changes on author entity directly
$em->merge($author);

我更喜欢这种方法,因为它使您有机会在添加新闻时进行额外的检查或控制,从而使代码可重用且易于阅读

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多