2012-01-02 180 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這種方法,因爲它讓你有機會做額外的檢查或控制,同時增加的消息,使得可重複使用,易於閱讀代碼