Search code examples
phpyiimany-to-manyrelationgii

Using Many to Many relations in yii


I am currently trying to display/retrieve data from my database using Yii framework relations which were auto generated by Gii. (MANY_MANY)

User Model contains:

return array(
        'memberOfTeams' => array(self::MANY_MANY, 'UsersTeam', '{{teamMembers}}(userId, teamId)'),
    );

UserTeam Model contains:

    return array(
        'teamMembers' => array(self::MANY_MANY, 'User', '{{teamMembers}}(teamId, userId)'),
    );

Currently I am working on the User view called profile.php . All I am trying to accomplish is to display the current user with all the teams assigned to him.

teamMembers contains teamId and userId.

How would I write this query?

I have this currently

<?php echo CHtml::dropDownList("teamName", 'id', Chtml::listData(UsersTeam::model()->with('teamMembers')->findAll(teamMembers.userId, array($model->id)), 'id', 'teamName'),array('empty'=>'Select Team')); ?>

I am able to get all the information if I use findAll(), but I want only teams that the user is assigned to.


Solution

  • A project of mine does something similar:

    MANY_MANY relation between shop and card, this dataprovider is used to display a list of shops linked to a specific card:

    $shopDataProvider=new CActiveDataProvider( 'Shop',
                array(
                    'criteria'=>array(
                        'with'=>array('cardShop'),
                        'condition'=>'cardShop.card_id=:cardId',
                        'params'=>array(':cardId'=>$id),
                        'order'=>'t.id DESC',
                        'together'=>true,
                    ),
                )
            );