Error When Foreign Key Is Null


is there a way to avoid the error

Trying to get property of non-object 

when the value of a foreign key is NULL.

I am a Yii beginner and I am wondering, because the following MySQL query on the command line (not in Yii) retrieves data even if the foreign key composer_Id is NULL:

SELECT * FROM `tbl_main` AS t

LEFT JOIN tbl_related AS rel

ON t.composer_Id = rel.Id

Using relations in Yii ActiveRecord I get an error, when there are records having an empty foreign key.

Relations in tbl_main model:

'composer'=>array(self::BELONGS_TO, 'tbl_related', 'composer_Id')

Relations in tbl_related model:

'items'=>array(self::HAS_MANY, 'tbl_main', 'composer_Id')

Thank you for hints.

Hello. The way I handle such situation is to always check if the relation does not return null. You can check it here. Or if you are using CGridView, you can use it like this :



      'name' => 'apartment_unique_id',

      'type' => 'raw',

      'value'=> 'Apartment::getApartmentUniqueID($data->apartment_id)',



In my model :

public static function getApartmentUniqueID($apartmentId) {

    if($model = Apartment::model()->findByPk($apartmentId)) {

        return CHtml::link($model->apartment_unique_id,array('apartment/view','id'=>$model->apartment_unique_id));

    } else {

        return "Apartment Not Found";



So instead of calling the relation directly you can call the function that will check whether the relation return null value or not

Yii executing the query successfully. Just we have to check the data null or not When we use it. When i checked this, My code was working perfectly .

One technique is to use the CHtml::value() method to fetch the value from the model (and hence from the database) - this method implies testing for null.

How did I not know about this method? Thanks for the info.

Well Keith, thanks for the heads up :wink: - however I do not know why ;-). I’ve just seen it enough times when going through the inner workings of Yii.

Do you know about my extension RelatedSearchBehavior? I use CHtml::value() in there too. Besides making fields from relations searcheable and sortible, it also provides aliases to related fields for which CHtml::value() is used. Even with your 'Master Member" status, I think you’ll like the extension!

1 Like