2011-06-14 52 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