yiibelongs-toyii-relations

Yii relation Trying to get property of non-object


I've these tables

estudiantes

id_estudiante pk nombre_estudiante

evaluaciones

id_evaluacion pk evaluacion_estudiante evaluacion_asignatura

asignaturas

id_asignatura pk nombre_asignatura

in evaluaciones model relations

return array(
                'estudiantes'=>array(self::BELONGS_TO, 'Estudiantes', 'evaluacion_estudiante'),
        );

evaluaciones's _view file i have this

<?php echo CHtml::encode($data->estudiantes->nombre_estudiante); ?>

and there is an error on that line, it seems to be a problem with relations.. but i cant solve it.

Trying to get property of non-object


Solution

  • This error occurs when you are trying to echo something that doesn't exist.

    The best way to get rid of this error is to check your value first before rendering it for output.

    you can do:

    if(!empty($data->estudiantes->nombre_estudiante))
    <?php echo CHtml::encode($data->estudiantes->nombre_estudiante); ?>
    

    or using ternary:

    <?php (!empty($data->estudiantes->nombre_estudiante)?
    echo CHtml::encode($data->estudiantes->nombre_estudiante) : "null value"; ?>