2011-06-14 51 views
6

如何在Yii中建立與關係的裝置?例如,有帖子可以有評論,我如何參考夾具中的帖子ID來創建評論?Yii中的關係裝置

後夾具:

return array(
    'post1'=>array(
    'title'=>'My title', 
    'body'=>'My text', 
), 
    ... 

評論夾具:

return array(
    'comment1'=>array(
    'text'=>'Comment text...', 
    'post_id'=> ??? 
), 
+0

我們在這裏談論關係查詢嗎? – 2011-06-15 02:35:03

+0

不是嗎?我只想創建與生產系統中的關係類似的裝置(用於單元測試)。 – 2011-06-15 13:22:16

+0

我的不好。我會先看看它。 – 2011-06-15 13:29:43

回答

5

我不知道是否有做一個動態的方式,但下面應該工作:

帖子夾具:

return array(
    'post1' => array(
    'id' => 1 
    'title' => 'My title', 
    'body' => 'My text', 
), 

評論夾具:

return array(
    'comment1' => array(
    'text' => 'Comment text...', 
    'post_id' => 1 
), 
+0

如果有人想知道,這確實有效 - **儘管文檔中提到了動態生成的「id」字段,並聲明不設置它們。** – 2013-07-24 22:15:42

+0

由於夾具加載的順序由php readdir命令列出夾具文件決定,因此可能需要暫時禁用外鍵約束*。 – clapas 2013-08-13 11:20:42

4

據我瞭解,你可以使用init腳本,而不是古典裝置。該Yii documentation寫着:

這也可能是我們不喜歡重置 表,即截斷它與夾具數據插入它的默認方式。如果 是這種情況,我們可以爲 特定夾具文件編寫一個初始化腳本。該腳本必須命名爲後綴爲.init.php的表名 。例如,Post表的 的初始化腳本將爲Post.init.php。當CDbFixtureManager看到 這個腳本時,它將執行這個腳本而不是使用默認的 方式來重置表格。

所以你的情況,而不必protected/tests/fixtures/Comment.php,你就必須protected/tests/fixtures/Comment.init.php它做到這一點:

// the $this variable refers to the CBdFixtureManager instance 
$this->truncateTable($tableName); 
$post = $this->getRecord('Post','post1'); // get dependent fixture 

// define new fixture 
$commentAttributes = array(
    'text' => 'Comment text...', 
    'post_id' => $post->id 
); 
$comment = new Comment; 
$comment->setAttributes($commentAttributes); 
if(!$comment->save()) throw new CException('Unable to save fixture'); 

// add new row primary key 
$pk = Comment::model()->getTableSchema()->primaryKey; 
if(is_string($pk)) 
    $commentAttributes[$pk] = $comment->$pk; 
elseif(is_array($pk)) 
    foreach($pk as $key) 
    $commentAttributes[$key] = $comment->$key; 

$this->_rows['Comment']['comment1'] = $commentAttributes; 
$this->_records['Comment']['comment1'] = 'Comment'; 

雖然我知道這是一個非常晚的答覆,這應該解決您的問題。由於我在這裏使用谷歌搜索,我希望能幫助其他需要此信息的人。

+0

感謝您的回覆,即使有時間延遲!我希望它能幫助未來的人。 – 2012-03-24 01:55:16

2

我知道它已經回答了,但我認爲這是一個更好的答案。 是的,你可以使用動態字段的關係:

後夾具:

return array(
    'post1' => array(
    'title' => 'My title', 
    'body' => 'My text', 
), 

評論夾具:

return array(
    'comment1' => array(
    'text' => 'Comment text...', 
    'post_id' => $this->getRecord('post', 'post1')->id 
), 

PostTest.php

public $fixtures=array(
    'post'=>'Post', 
    ... 
); 

Yii的文檔CDbFixtureManager

+0

我嘗試過,但它沒有奏效,是什麼不同,我必須做bootstrap或配置? cdbFixtureManager中的_records對我而言始終爲空 – FabioCosta 2012-09-12 11:52:46

+0

什麼是「_records」? 它是否適用於硬編碼ID?如果不是,那麼它與我的答案無關,你應該尋求建立測試和夾具的幫助。 提示:我認爲$ fixture數組中的順序很重要,因此請確保首先包含主表(這裏'post'是$ fixtures中的第一個元素,然後'comment'應該遵循)。 – kcsoft 2012-09-12 12:13:12

+0

除了使用硬編碼ID之外,不需要其他配置。我的猜測是你拼錯了一些東西。例如cdbFixtureManager沒有任何「getRecords」方法。它有「getRecord」,它應該返回一個ActiveRecord對象。也許你已經使用「 - > id」來獲得id,但它應該匹配你模型中的id。 – kcsoft 2012-09-12 12:28:25