我对将实体插入数据库存有疑问。我有两个模型:
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;
}
}
要添加新消息,我必须同时包含User
和News
类(如果它们位于单独的文件中,例如UserModel.php和NewsModel.php)并编写代码:
$news = new News()
$news->setTitle('TEST title');
$news->setAuthor($database->find('User', 1));
$database->persist($news);
我的问题是:有没有办法插入新闻而不包括User
类?
答案 0 :(得分:7)
您无需实际加载用户。
相反,您可以使用reference proxy:
<?PHP
$news = new News()
$news->setTitle('TEST title');
$news->setAuthor($em->getReference('User',1));
$em->persist($news);
答案 1 :(得分:1)
你可以做的另一件事(以更面向对象的方式思考)是在你的用户实体上添加一个名为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);
}
并将cascade persist添加到您的映射中:
/**
* @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);
我更喜欢这种方法,因为它让您有机会在添加新闻时进行额外的检查或控制,从而实现可重复使用且易于阅读的代码