AR Relations difficulties

I’m having some difficulties understanding AR relations. What I want is simple. When I’m managing (actionAdmin) a user, I want to select the user type from a pulldown. I can’t manage to get the data from the foreign table.

I have the following tables:


CREATE TABLE `User` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `usertypeid` int(11) NOT NULL,

  `username` varchar(50) NOT NULL,

  `password` varchar(32) NOT NULL,

  `entry_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,

  PRIMARY KEY (`id`)

) ENGINE=MyISAM  DEFAULT CHARSET=utf8;


CREATE TABLE `UserType` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `type` varchar(50) NOT NULL,

  PRIMARY KEY (`id`)

) ENGINE=MyISAM  DEFAULT CHARSET=utf8;

In yiic shell I created the models and crud files.

In User I defined the folowing relation:




public function relations()

{

	return array(

		'usertypeid'=>array(self::BELONGS_TO, 'UserType', 'id'),

	);

}



In UserType the following:




public function relations()

{

	return array(

		'user'=>array(self::HAS_MANY, 'User', 'usertypeid'),

	);

}



In UserController in the actionAdmin function I have this:




$models=User::model()->with('usertypeid')->findAll();



This doesn’t work however. What am I doing wrong here?

Specify the foreign key in the relationship declaration.




public function relations()

{

  return array(

    'usertypeid'=>array(self::BELONGS_TO, 'UserType', 'usertypeid'),

  );

}



You don’t need to declare a relationship in the other model class.

/Tommy

Thank you for your quick reply Tommy.

I tried your suggestion, but the variable $models still does not contain related items.

I tried something else:

In User I did what you suggested. In UserType I did:




public function relations()

{

	return array(

		'type'=>array(self::HAS_MANY, 'User', 'usertypeid'),

	);

		

}

And finaly in UserController I did:




$models=User::model()->with('usertypeid.type')->find();



This gives me the result I wanted. I still don’t understand why.

How did you access the $models variable?

Since you used findall() one proper way would be




foreach ($models as $model)

  echo $model->usertypeid->type;



/Tommy

Tommy, you are completely right. I was using Netbeans debug mode to examine the $model object. It seems not completely bug free.

With plain echoing everything works just fine.

Thanks a lot for your help!

grtz,

Wouter