Problem with call to 'self::STAT' relational attribute.

I’m stuck with another questionable issue.

I basically intend to test whether a new field gets added to DB, upon doing a simple save() function.

Here is the test for the same,



public function testProspectsCreate()


{	


	$list = $this->lists('list1');


	$this->assertEquals(4, $list->totalProspects); // Checking number of prospects before creating


	


        // Creating new prospect and associated fields


	$newProspect = new Prospects;


	$newProspect->setAttributes(array(


		'email'=>'test@test.com',


                'phone_mobile'=>99812637633


	));


	$newProspect->save();


	$newProspect->saveOtherRecords($list->id);





	$this->assertEquals(5, $list->totalProspects); // Checking number of prospects after creating


}

This should obviously work, there are 4 records before creating a new one, and 5 afterwards. However, it does not.

It keeps throwing the error ‘Failed asserting that ‘4’ matches expected 5.’

But, when I check inside the test database, the record does get created. Also, if I comment out the second line in the function,



// $this->assertEquals(4, $list->totalProspects);

then the test runs fine.

This tells me, if I call ‘$list->totalProspects’ before creating a new record (which gives me 4), then it returns to me the same value it had, later on as well. Whereas, it should return the new value (which is ‘5’).

Here is the code for the ‘totalProspects’ relational attribute,



'totalProspects'=>array(self::STAT, 'ListProspects', 'prospect_list_id'),

I wonder how I get into such impossible problems. :(

What could be the reason for such an error?

Once $list->totalProspects has been fetched from database, it won’t be reloaded on subsequent accesses (by design). Try


$list->getRelated('totalProspects', true)

instead.

That worked! Well, really appreciate your answer. Would try to find out the reason myself, but, could you also tell which part of the code design makes the previous one behave that way? I want to know why it does not reload when called again, and why so.

Well, most of the time there is no need for that. Imagine that every time you access a relation (the relation $property) in your code it would get reloaded - means db queries for no reason. The cases were fresh data is a requirement are very rare (like in a console command or in test cases like yours).

I see. So basically, to save some processing. Thanks.