Question

So I'm working on some unit tests and relational fixtures.

I'm creating a model dynamically like:

$model = CActiveRecord::model('Post');
$post = $model->findByPk(1);

But after that I cannot for some reason get $post->id. I traced the problem to CActiveRecord class:

public function __get($name)
{
    if(isset($this->_attributes[$name]))
        return $this->_attributes[$name];
...

Where $name = "id". It says that $this->_attributes[$name] does not exist! As a matter of fact _attributes is empty.

My Post class does not define id (or any other properties) as a public property and I don't want to do so either. I just let the AR map it to table columns for me.

What am I missing?

Edit 1

My fixtures are regular Yii fixtures - nothing really special about them.

What differs is the way I load them really. I extended the CDbFixtureManager to be able to specify the order in which they should be loaded by overloading load() method. Only thing of interest that actually fails is that in the fixtures that have foreign keys I use the following:

'comment1' => array('post_id' => $this->getRecord('Post', 'post1')->id);

That's where it fails. getRecord returns the actual Post record (since I know the Post fixture has already been successfully loaded and exists in DB), but on the ->id part I get an exception about that attribute not existing.

If I go into Post model and add public $id; to it, then everything works! But I'm not sure if it's good practice to go about declaring all properties public like that.

Was it helpful?

Solution 2

I think I found the root cause of this issue for me. While my FixtureManager was using the testdb DBConnection, the models still used the regular one.

For whatever reason, my debugger was giving me misleading errors like the one described in my original post.

Once I was able to set the DBConnection of all Models in the unit test the puzzle snapped into place and everything is now working smoothly!

OTHER TIPS

If you look at this page carefully: http://www.yiiframework.com/doc/guide/1.1/en/test.unit

you'll see that they use an array form for retrieving fixtures:

$this->posts['sample1']['id']

There is an alias defined in their fixture array for each record and fixture items aren't loaded as models really ...

Does that help? If not, it would be helpful to see your fixture file :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top