Relational Active Record For User Friend Relation

Hi,

I’m quite new to Yii. And I’m yet to explore its features & capabilities.

I was developing a small app, and I faced a difficulty with Relation AR.

My scenario:

Two tables - user & friends




CREATE TABLE IF NOT EXISTS `user` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `username` varchar(20) NOT NULL,

  `password` varchar(50) NOT NULL,

  `name` varchar(100) NOT NULL,

  `email` varchar(100) NOT NULL,

  PRIMARY KEY (`id`)

) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;


CREATE TABLE IF NOT EXISTS `friend` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `user_id` int(11) NOT NULL,

  `friend_user_id` int(11) NOT NULL,

  `status` varchar(1) NOT NULL,

  PRIMARY KEY (`id`),

  KEY `user_id` (`user_id`),

  KEY `friend_user_id` (`friend_user_id`)

) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;


--

ALTER TABLE `friend`

  ADD CONSTRAINT `friend_ibfk_2` FOREIGN KEY (`friend_user_id`) REFERENCES `user` (`id`),

  ADD CONSTRAINT `friend_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`);



Relations I have in my user model




return array(

	'friends' => array(self::HAS_MANY, 'Friend', 'friend_user_id'),

	'friends1' => array(self::HAS_MANY, 'Friend', 'user_id'),

);



And friend model




return array(

	'friendUser' => array(self::BELONGS_TO, 'User', 'friend_user_id'),

	'user' => array(self::BELONGS_TO, 'User', 'user_id'),

);

I’m fetching as

$model=User::model()->with(‘friends1’)->findByPk($id);

OK, my intent : I want the friends ‘complete’ info from user table for each friend of the user.

(If user 1 has two friends - 2 & 3, I want complete details of user 2 & 3 when I look for user 1)

How can I achieve that?

With the present relations all I can get the user_id’s of the friends.

Any info regarding this will be very much appreciated.

TIA.

(btw, is it advisable to keep only the login info in user table and keep rest of the profile info in ‘profile’ table?)

I think you want:




$model=User::model()->with('friends1.user')->findByPk($id);



Then you can access the full user details in this sort of manner:




foreach ($model->friends1 as $friend)

{

    // Get full details via $friend->user

}



Thanks @Keith .

But just after posting the question I found, following line does exactly what I needed


echo $model->friends1[0]->friendUser->name;

now of course I can iterate through the "$model->friends1" to get what I desired.

RAR simply awesome. Last night I spend more than a hour learning SQL Joins. :P

If you include the relation in your with expression, the data will be loaded eagerly. Otherwise, an extra database query will be performed for each set of details that you access.