Relations and model's functions

Hello again, I'll try to explain my problem as simple as posssible:

I have a Model Invoice and a Model InvoiceDetail

In Invoice model, in the relations method I have (among others) the following relation declaration:

So I can do $invoice->total to get the total amount of some invoice;

This works perfect if I load an invoice in the controller. (or use total in a view)

But, I have the following:

In mi Invoice model I have a public function (non static) called saveInDiary, where I do the following:

But this code saves 0 (zero) in the total property of diary.

But if I do this:

It saves the correct value (the real total)

What I'm doing wrong?

Or it's not possible to use relations from inside a model?

Any suggestion?

I understood your problem.

Not sure, but it seems that $this and Invoice::model()->findByPk($this->id) are not returning the same class. Try to use a print_r() function to check it.

Anyway, why put saveInDiary in the Invoice model? You should not put a business-control inside a model. This method should reside in the Controller, I think.

I found the problem… I will try to explain:

When I do this

Please, check this, is not a complicated example… and all this has be done in a controller.

The related objects are only fetched once. So if you access $invoice->total and change the related data later, total will not get updated until you fetch a fresh $invoice.

Exactly what I'm trying to say… but this is the expected behavior?

Why?

Because otherwhise there would be another query, whenever you access a related property - not what most users want. ;) Not sure if refresh() might clean the fetched related records again. Maybe give that a try?