Search code examples
phpyiiyii-relations

Yii CActiveDataProvider Many to Many


I do not understand how to implement a many to many relation in CActiveDataProvider.

At first the situation, I have one Model "Company" with following relations:

return array(

        'owner'     => array(self::HAS_ONE, 'User', 'user_id'),
        'admins'    => array(self::MANY_MANY, 'User', '{{company_user}}(company_id,user_id)', 'condition' => 'is_admin = 1'),
        'members'   => array(self::MANY_MANY, 'User', '{{company_user}}(company_id,user_id)'),
        'standard_members' => array(self::MANY_MANY, 'User', '{{company_user}}(company_id,user_id)', 'condition' => 'is_admin = 0'),
);

Now I want to get all admins of a company. Normally I did:

$company = Company::model()->find('company_id=1');
var_dump($company->with('admins')->findAll());

So I have all administrators of a company.

But I did not parse, how to do it with a CActiveDataProvider.

$dataProvider_admins = new CActiveDataProvider('Company', array(

'criteria' => array(

    'with' => array(

        'admins' => array('condition' => 'company_id='.$company->id)
    ),
),
'pagination' => array(

    'pageSize' => 20,
),
));

var_dump($dataProvider_admins->getData());

But with this way I get a company record with all administrators, but not an array containing all administrators.

Update: I could create an Model for the relation table {{company_user}} and use this, but I do not think its the right way, isn't it?


Solution

  • I found a good solution. I use the model, which I want to display. In this case, an administrator is an user.

    Now I join the tables manually.

    $dataProvider_admins = new CActiveDataProvider('User', array(
    
        'criteria' => array(
    
            'join' => 'LEFT JOIN `{{company_user}}` ON `id` = `user_id` AND `company_id` = '.intval($company->id),
            'with' => array('profile'),
        ),
        'pagination' => array(
            'pageSize' => 20,
        ),
    ));
    

    The whole CActiveDataProvider will be returned by the Companymodel, so it is logical encapsulated.

    $dataProvider = Company::model()->find('id=5')->adminsDataProvider;
    

    I hope the solutions helps somebody.