Relational lighting in Yii

How to set up fixtures with relationships in Yii? For example, if posts can contain comments, how can I refer to the post id in the document to create comments?

Post fixture:

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

Comment Component:

 return array( 'comment1'=>array( 'text'=>'Comment text...', 'post_id'=> ??? ), 
+6
source share
3 answers

I don't know if there is a dynamic way to do this, but the following should work:

Post fixture:

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

Comment Component:

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

As I understand it, you can use initialization scripts instead of classic fixtures. Yii 's documentation states:

It is also possible that we do not like the default method of dumping the table, i.e. truncating it and pasting it with the device data. If so, we can write an initialization script for a specific binding file. The script should be named after the table suffix with .init.php. For example, the initialization script for the Post Table will be Post.init.php. When the CDbFixtureManager sees this script, it will execute this script instead of using the default path to the reset table.

So, in your case, instead of protected/tests/fixtures/Comment.php , you will have protected/tests/fixtures/Comment.init.php that does this:

 // 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'; 

Although I understand this is a very late answer, this should solve your problem. Since I got googling here, I was hoping I could help someone who needs this information.

+4
source

I know this has already been answered, but I think this is the best answer. Yes, you can use dynamic fields for relationships:

Post fixture:

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

Comment Component:

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

PostTest.php

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

Yii docs CDbFixtureManager

+2
source

Source: https://habr.com/ru/post/890551/


All Articles