问题
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