原则2.1——实体插入


Doctrine 2.1 - entity inserting

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

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类的情况下插入新闻?

您不需要实际加载用户。

相反,您可以使用一个参考代理:

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

您可以做的另一件事(以更面向对象的方式思考)是在用户实体上添加一个名为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);

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