AR lazy loading

I have two tables - tblCars and nclTypes.

nclTypes is a nomenclature, and its ID is foreign key for tblCars.

I have a declared a relation in the model class called type

'type' => array (self::HAS_ONE, 'Type', 'typeID');

In the documentation is said, that if I try to access $someCar->type it should load Type model:

$someCar = Car::model()->findByPk('myCar');


var_dump($someCar->type);

But it does not - it returns null.

It works if include "with":

$someCar = Car::model()->with('type')->findByPk('myCar');


var_dump($someCar->type);

Do I have to do this every time and for every relation?

And there is one thing more, that boders me - If we have similar scenario on the one above, but in the tblCars foreign key columns is named "someStrangeNameForForeignKey", how I should define the relation in the Car class?

Is it possible to make a relation private or protected - let's say I don't want to use someStrangeNameForForeignKey for property name, but simplier "FK". Can I make the someStrangeNameForForeignKey private or protected and expose it throught getter/setter?

$someCar = Car::model()->findByPk('myCar');

var_dump($someCar->type);

The above may not work because it goes through a __get() magic method.  Try something like:

var_dump($someCar->type->attribute);

where attribute is an attribute of type

…ok, so now I got

Trying to get property of non-object
which is not so surprisingly… :)

I am confused - I saw two different scenarios, probably caused by same reason - in the one case without 'with' my class returns NULL… In the other case it returns the column value (the foreign key value) only like a string…

It is the same result, no matter if I am trying to dump the hole class or some of its properties…

When I add 'with' in the first case it just works as expected, in the second case nothing changes and it still returns just the value of the key.

And one extra question - In the scenario I've described in my previous post, what is correct relation type - HAS_ONE or BELONGS_TO?

Which version of Yii are you using? Could you turn on logging and see what are the SQLs generated for both lazy and eager loading?

Is there a local column name conflicting with the foreign table name?  That would make sense to me

yeah, that could be very likely.

Thanks for your answers!

I've resloved the error it was because of visibility modificator of the foreign key property - it was protected… But that raises another question: I have a property userEmail, which is the same as the table column. I want to have property 'email' not 'userEmail'.

I've made getters/setters for it. How can I hide 'userEmail' property (how can I make it protected) and in the same time to use this column in relations?

You mean hide it as, not let it be set with CModel::setAttributes() ?  Look up safeAttributes()