Left Join Activerecord Relation Returns "trying To Get Property Of Non-Object "

To be short, I know that the error comes out because active record can’t find the record in the related model. I have searched for the solution and a lot of them left unanswered. It seems the solution so far is as mentioned in this link:




$cinema = Cinema::model()->find(); // get a cinema instance, assuming there is at least one row in the database.

$city = $cinema->city; // get the relation 

if ($city !== null) {

    // $city is a valid model

} else {

    // $city is null, the corresponding row does not exist in the database

}



or




CHtml::value($model, 'city.name');



My question: Isn’t there any way to avoid checking the relation manually (if it’s null) or using CHtml::value? Can I just use $cinema->city->name and if active record can’t find the record, it doesn’t raise an error?

Well … you could implement setCity() and getCity() methods for your model and return a new (empty) City model if one hasn’t been set previously. But that would be a bit hackish, I guess. Your best bet is probably sticking to CHtml::value().

Thanks for your reply.

I thought we can set something in the model’s relation so it can return the field as null even when the record can’t be found (like in normal SQL LEFT JOIN).

Btw, if I’m using with(), I see in the profiling the SQL will be run as a whole (eager loading), but how to get the whole record? I tried using getAttributes() but it only returns the attributes from current model (related model’s are omitted). Really curious about this, if there is any method that can return the whole record of active record query, it surely makes life easier.