Attempt to assign property of non-object error

I am getting the error "Attempt to assign property of non-object" on the line

$player->animalid = $animal->id;

The player record has animalid as one of the fields. The code attempts to do the following:

  1. Create a new animal record (with auto_increment id key)

  2. Set the player record’s animalid field with the new animal id

  3. Save the player record.




if($animal->validate())

{

	$player = Player::model()->findAllByPk(Yii::app()->user->id);

	if (!$player)

	{

		throw new CHttpException(500,'Unable to read the player record.  Contact the administrator.');

	}

	else

	{

		$animal->save();

		$player->animalid = $animal->id;

		$player->save();

		$this->redirect(array('post/list'));

	}

}



It must be some basic error here.

Thanks.

It looks like $animal doesn’t exist and it therefore can’t assign the ‘id’ property of $animal to the ‘animalid’ property of $player.

So let me state the obvious and say that something’s wrong with $animal ;) How are you instantiating $animal?

findAllByPk returns an array of objects, in your case it should contain one object.

Please try findByPk instead.

Thank you Drech and sluderitz.

Sluderitz was right. FindAllByPk was the error.

Thank you very much for such fast response.