Trying to get property of non-object

I don’t understand how to fight with “Trying to get property of non-object” problem when using Models.

Example:

class User extends CActiveRecord{

public function relations()

{


	// NOTE: you may need to adjust the relation name and the related


	// class name for the relations automatically generated below.


	return array(			


		'company' => array(self::BELONGS_TO, 'Company', 'companyId'),


	);


}

Then I get all records from data base

$rows = User::model()->findAll();

and print User and User company name.

foreach ($rows as $row){

 print $row->name.' '.$row->company->name.'<br/>';

}

Everything is fine until in User table I insert 0 in companyId and because in company table there is no row with such id, I get "Trying to get property of non-object" error. Instead of that I want get empty string in every case when there is no related record, not error. Is this possible?

Please use the code tags (<> icon in full editor) to make your code better readable.




// print available informations

foreach ($rows as $row) {

	print $row->name;

	if (!empty($row->company)) {

		print ' '.$row->company->name;

	}

	print '<br/>';

}

// or print only informations where related data is available

foreach ($rows as $row) {

	if (!empty($row->company)) {

		print $row->name.' '.$row->company->name.'<br/>';

	}

}



Or in this thread the same problem was discuessed and already solved.

This is not good solution for me. I don’t want to write in every output <?=!empty($row->company->name)?$row->company->name:’’?>

One of solution could be this:




<?

function print2($p1,$p2)

{

   if (!empty($p1->$p2))

      return $p1->$p2;

}

print2($row->company,'name');

?>



Maybe someone know better solution to this problem?

Better solution or not, IIRC you may try removing the E_STRICT php error_reporting setting. Before it became default (again IIRC) I think we didn’t see this error message in your use case. Also IIRC, it may have been because of a change in the framework, to handle php warnings as errors.

/Tommy

One solution could be to override the CActiveRecord::afterFind() method and doing the check if an related model or an attribute is empty there.

But I never tested this myself so it is only a suggestion based on reading the API documentation