[SOLVED] Relations in Yii

Hey,

[EDIT:]

[size="5"][font="Arial Black"][color="#FF0000"]SOLVED[/color][/font][/size] , thx to RuudBurger

for the answer see below long post, ye the one with all the code in it)

I’m new to Yii (and MCV) but i got some experience in PHP (mostly PHP 4)

I was wondering how to do relations exactly.

I’ll explain what i wanna do exactly.

I have 2 tables named Users and Groups.

Those tables have a Many to Many relation (N:N).

To be able to do that i made a 3rd table called Relations witch holds the relation between the 2 tables obviously.

thingy

Basically because each group can have several users and each user can have several groups.

So have 3 models now and for the Users and Groups tables i have controllers too (created with the model en crud command line shell.

now i wanna make a command in the groups controller getGroupsByUserID and in the users controller getUsersByGroupID.

the question is now where do i write those functions/methods and how do i built the internal relations trough the table Relations.

I wanted to do it with the Yii relations function but there is very little documentation about this topic.

Anyone wanna share some explanations ?

I think, this can help you: http://www.yiiframework.com/files/yii-blog-1.0.8.pdf

It’s on page 17.

hope it helps.

Well it does and it doesn’t

It doesn’t really give an example of a MANY_to_Many relationship and those examples are only with 2 tables, i have 3 tables

I guess i need 2 relations in the model of users and 2 relations in the groups model.

maybe a relation to users and groups in the model table aswell

but then i guess its a 1 to Many to relations from both groups and users model to the Relations model and a Many to 1 from the relations model to the 2 other models

that’s the point where i don’t get the Many_to_Many relation in the models

Hah, with a help RuudBurger i managed to get it working, for people who want to know how it’s done now i’ll show you my current code:

you can name the tables how you want and the classes and all but this isn’t optimized yet.

SQL:


--

-- Table structure for table `rel_users_usergroups`

--


CREATE TABLE IF NOT EXISTS `rel_users_usergroups` (

  `ID` int(11) NOT NULL auto_increment,

  `user_id` int(11) NOT NULL,

  `group_id` int(11) NOT NULL,

  PRIMARY KEY  (`ID`)

) ENGINE=InnoDB  DEFAULT CHARSET=latin1 ;


-- --------------------------------------------------------


--

-- Table structure for table `Users`

--


CREATE TABLE IF NOT EXISTS `Users` (

  `user_id` int(11) NOT NULL auto_increment,

  `username` varchar(32) NOT NULL,

  `password` varchar(50) NOT NULL,

  `email` varchar(200) NOT NULL,

  `roleid` int(11) NOT NULL,

  PRIMARY KEY  (`user_id`)

) ENGINE=MyISAM  DEFAULT CHARSET=latin1 ;


-- --------------------------------------------------------


--

-- Table structure for table `Users_Groups`

--


CREATE TABLE IF NOT EXISTS `Users_Groups` (

  `group_id` int(11) NOT NULL auto_increment,

  `name` varchar(50) NOT NULL,

  `short` varchar(50) NOT NULL COMMENT 'capital reference name',

  PRIMARY KEY  (`group_id`)

) ENGINE=MyISAM  DEFAULT CHARSET=latin1 ;

At this point you can fill in a user, a group and a relation into your database to avoid errors from here on

yiic shell:




model Users

model Users_Groups

model rel_users_usergroups

crud Users

crud Users_Groups



In models/Users.php

added relation:




/**

	 * @return array relational rules.

	 */

	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(

		        'groups' => array(self::MANY_MANY, 'Users_Groups', 'rel_users_usergroups(user_id, group_id)')

        );

		

	}



in contollers/UsersController.php

[EDIT: Added RuudBurger’s suggestions]

new action:




/**

	 * Shows a particular model in detail.

	 */

	public function actionDetail()

	{

		$user = Users::model()->with('groups')->findByPk($_GET['id']);

                $this->render('detail', array('user'=> $user));

	}



added views/users/detail.php

[EDIT: Added RuudBurger’s suggestions]


<h2>View User Details for <?php echo $model->username; ?></h2>


<div class="actionBar">

[<?php echo CHtml::link('Users List',array('list')); ?>]

[<?php echo CHtml::link('New Users',array('create')); ?>]

[<?php echo CHtml::link('Update Users',array('update','id'=>$user->user_id)); ?>]

[<?php echo CHtml::linkButton('Delete Users',array('submit'=>array('delete','id'=>$user->user_id),'confirm'=>'Are you sure?')); ?>

]

[<?php echo CHtml::link('Manage Users',array('admin')); ?>]

</div>


<table class="dataGrid">

<tr>

	<th class="label"><?php echo CHtml::encode($user->getAttributeLabel('username')); ?>

</th>

    <td><?php echo CHtml::encode($user->username); ?>

</td>

</tr>

<tr>

	<th class="label"><?php echo CHtml::encode($user->getAttributeLabel('password')); ?>

</th>

    <td><?php echo CHtml::encode($user->password); ?>

</td>

</tr>

<tr>

	<th class="label"><?php echo CHtml::encode($user->getAttributeLabel('email')); ?>

</th>

    <td><?php echo CHtml::encode($user->email); ?>

</td>

</tr>

<tr>

	<th class="label">Groups:

</th>

    <td>

    <?php foreach($user->groups as $group)

    {

	 echo CHtml::link($group->name,array('users_Groups/detail','id'=>$group->group_id));

	} ?>

    </td>

</tr>


</table>



In models/Users_Groups.php

added relation:




/**

	 * @return array relational rules.

	 */

	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(

		        'users' => array(self::MANY_MANY, 'Users', 'rel_users_usergroups(group_id, user_id)')

        );

		

	}



in contollers/Users_GroupsController.php

[EDIT: Added RuudBurger’s suggestions]

new action:




         /**

	 * Shows a particular model in detail.

	 */

	public function actionDetail()

	{

		$group= Users_Groups::model()->with('users')->findByPk($_GET['id']);

                $this->render('detail', array('group'=> $group));

	}



added views/users_Groups/detail.php

[EDIT: Added RuudBurger’s suggestions]


<h2>View Group Details for <?php echo $group->name; ?></h2>


<div class="actionBar">

[<?php echo CHtml::link('Groups List',array('list')); ?>]

[<?php echo CHtml::link('New Group',array('create')); ?>]

[<?php echo CHtml::link('Update Group',array('update','id'=>$group->group_id)); ?>]

[<?php echo CHtml::linkButton('Delete Groups',array('submit'=>array('delete','id'=>$group->group_id),'confirm'=>'Are you sure?')); ?>

]

[<?php echo CHtml::link('Manage Groups',array('admin')); ?>]

</div>


<table class="dataGrid">

<tr>

	<th class="label"><?php echo CHtml::encode($group->getAttributeLabel('name')); ?>

</th>

    <td><?php echo CHtml::encode($group->name); ?>

</td>

</tr>

<tr>

	<th class="label"><?php echo CHtml::encode($group->getAttributeLabel('short')); ?>

</th>

    <td><?php echo CHtml::encode($group->short); ?>

</td>

</tr>


<tr>

	<th class="label">Users:

</th>

    <td>

    <?php foreach($group->users as $user)

    {

	 echo CHtml::link($user->username,array('users/detail','id'=>$user->user_id));

	} ?>

    </td>

</tr>


</table>



[b]One final note:

You might want to add the page details to your rules, or you might end up in not seeing your page at all due to unauthorised access.[/b]

Dont know what the $this->loadUsers() does. But I think you can replace those calls with what you load in the $user.

$model->user_id ==> $user->user_id

$model->getAttributeLabel(‘username’) ==> $user->getAttributeLabel(‘username’) etc.

LoadUsers is there when you execute the curd shell command.

But you’re right i’ll edit it.

Oh and one other thing,

you have to do the same for Groups or UsersGroups or whatever ofc.

but then the other way around :P

solved, can some change this topic name to solved in stead of request?

Please edit your posts instead of adding new replies.