2012-01-02 83 views
3

我有关于将实体插入数据库的问题。我有两个型号:学说2.1 - 实体插入

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类?

+0

您的意思是:如何在没有用户的情况下制作新闻,因为新闻不应该有用户? – hakre 2012-01-02 16:32:19

+0

我的意思是说,我只能给用户的ID而不是整个用户对象。例如。像'$ news-> setAuthor(1);'或'INSERT INTO新闻值('测试标题',1);' – 2012-01-02 16:34:52

回答

6

您不需要实际加载用户。

相反,你可以使用一个reference proxy:你可以做(​​在一个更加面向对象的还挺方式思考)

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

谢谢!你还有一个问题。有没有办法做到这一点引用,但与其他列(不ID)? – 2012-01-06 23:24:42

+1

我不这么认为。您需要被引用实体的身份值。 – timdev 2012-01-08 01:27:35

+0

还有其他问题。这个'getReference()'比'find()'方法快吗? – 2012-01-11 00:07:17

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); 
} 

,并添加级联坚持到你的映射:

/** 
* @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); 

我preferr这种方法,因为它让你有机会做额外的检查或控制,同时增加的消息,使得可重复使用,易于阅读代码