Relations On New Record


I’m trying to pull a relation of a new record, mainly for validation purposes, but it will never return anything as it’s a new record.

It’s hard coded into CActiveRecord that unless you pass the refresh parameter along with it, HAS_MANY and HAS_ONE relations will return blanks.

Why is that? It’s a little annoying as it means I can’t create a model, lookup some relations on it, and validate it. I have to have special cases in for new records, which just go around the problem by setting isNewRecord to false, then back to true after it’s used.

I just can’t see a good case for not returning relevant records?


I suppose that the relations don’t logically exist until the record has been saved to the database, so it would be wrong of Yii to allow you to access them. You’d also have inconsistency in accessing the relations, because any that rely on the new record’s primary key will fail if the PK is assigned on creation by the database engine.

It seems more sensible to me to only allow access to the relations once the record has been fully created, rather than having to explain the caveats inherent in accessing them. Your workaround is essentially you taking responsibility for accessing the relations in an unsupported way.

Yes, I agree completely . It just seems to me that all of the issues you mention are still a problem when the record is in the database. The PK must still be assigned, if it’s not, you’ll get no relations (which would be expected). I’m thinking of a use case like:

$obj = new Thing;

$obj->area_id = 10;



$area = $obj->area;

So if I hadn’t set an area ID I could expect no areas.

I can understand any relations defined as [code]‘together’=>true/code] returning blanks as they wouldn’t be able to come down together.

There’s just doesn’t seem to be anything unexpected that would happen by allowing it. So I’m struggling to understand why it’s not.

I’ll leave it a day or so on here to see if someone knows a good reason why they shouldn’t be, then I’ll open up an Issue on GitHub to enable it and it can be discussed there.

I have the same problem.

And I found a solution for those who will look in the future.

Try $obj->getRelated(‘area’, true); instead $obj->area;