Trying to get property of non-object error in Yii

被刻印的时光 ゝ 提交于 2019-12-20 05:33:12

问题


Case 1: I get an array of CActiveRecords and try to loop over it as shown below:

foreach ($pendingTasks as $task)
    {
        if($task->task->employee_id=="1")
        {
            //some logic here
        }
    }

I get "Trying to get property of non-object "

Case 2: If I try:

$pendingTasks = TaskLog::model()->findByPk("1");
    if($pendingTasks->task->employee_id=="1")
    {
        //some logic here   
    }

This works. Why is this so? Am I doing any thing wrong here?


回答1:


Because of the tasks in $pendingTasks must not have a relation. You can check by simply adding an isset() like so:

foreach ($pendingTasks as $task) {
    if(isset($task->task) && $task->task->employee_id=="1") {
        //some logic here
    } else {
        echo "{$task->id} doesn't have a task relation";
    }
}

Assuming $pendingTasks are instances of TaskLog also.



来源:https://stackoverflow.com/questions/18335513/trying-to-get-property-of-non-object-error-in-yii

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!