Findbypk Vs Findbyattributes - Trying To Get Property Of Non-Object

[size="2"]$model = [/size][size="2"]User::model()->findByPk(1); // just assume 1 is valid[/size]

[size=“2”]$model->username; // this should return ‘John’[/size]

[size="2"]The model is not null as I dumped the values, but[/size]

I’ve got this error: Trying to get property of non-object.

But if i’ll use this,

$model = [size=“2”]User::model()->findByAttributes( array(‘username’ => ‘John’ ) );[/size]

[size="2"]$model->username;[/size]

[size="2"]It works,…[/size]

[size=“2”]What’s the proper way of using findByPk?, [/size]

[size="2"]though both of them return CActiveRecord type.

[/size]

Hi JbalTero,

Would you please post your code that produces the error?

In CGridView, I wanted to have a custom column value so in column I added,




array(

	'name' => 'Brgy_ID',

	'value' => '$data->toBrgyname($data->Brgy_ID)',

),



In model, I added public function,




public function toBrgyName($id) {

	// I want to extract a value for a specific attribute, which is "name"


	return Barangay::model()->findByPk($id); // This works fine, but I cannot extract the value


	// return Barangay::model()->findByPk($id)->name; // error: Trying to get property of non-object.

}



Make sure that the return value of findByPk() is an model object. Note that it can return null.




public function toBrgyName($id) {

	$barangay = Barangay::model()->findByPk($id);

	if ($barangay !== null) {

		return $barangay->name;

	} else {

		return 'no name';

	}

}



And, if the main model has a BELONGS_TO relation to "barangay" model, you can do this kind of job much more simple and easy.

Please refer to "Relational Active Record" section of the definitive guide.

Oh!, Thank you very much!, It works like magic!. There’s really a null value in one of the row. and know I know.