Question

I have three tables as roles, users and companies. and their relationships as

for Role.php

public function relations()
    {       
       return array(
        'userRoles' => array(self::HAS_MANY, 'UserRoles', 'id_roles'),
       );
    }

for User.php

public function relations()
    {
        return array(
            'userRoles' => array(self::HAS_MANY, 'UserRole', 'id_users'),
            'companies' => array(self::BELONGS_TO, 'Company', 'id_companies'),
        );
    }

For Company.php

public function relations()
    {
        return array(
        'idCompnayType' => array(self::BELONGS_TO, 'CompanyType', 'id_company_type'),
        'companies' => array(self::HAS_MANY, 'Company', 'id_companies'),
        );
    }

I have following functionality-

In roles table there are two three roles as SuperAdmin(Adds Company and their TenantAdmin for that company), TenantAdmin(Adds users to company) and Users.

I have done to functionality for adding all users and assign them roles.

But how can I display normal users as per their company when TenantAdmin for that company is logged in.

Était-ce utile?

La solution

You can use the option of through on your relation.

For Company model:

public function relations()
{
    return array(
        'idCompnayType' => array(self::BELONGS_TO, 'CompanyType', 'id_company_type'),
        'companies' => array(self::HAS_MANY, 'Company', 'id_companies'),
        'users' => array(self::HAS_MANY, 'User', 'id_companies'),
        'userRoles' => array(self::HAS_MANY,'UserRoles',array('id_users'=>'id_users'),'on'=>'userRoles.id_roles = 3','through'=>'users'),
    );
}

For UserRole model make sure you have a relationship like so:

public function relations()
{
    return array(
        'user' => array(self::BELONGS_TO, 'User', 'id_users'),
    );
}

A couple assumptions for this statement Primary Key in User is id_users, that the ID of the 'user' type is 3. This will give you an array of UserRole's that are the 'user' type. So you can easily list the users by using a foreach.

$user = User:model()->findByPk(Yii::app()->user->id);
$company = Company::model()->findByPk($user->id_companies);
foreach($company->userRoles as $userRole) {
    $user = $userRole->user;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top