I started using Yii just a few weeks ago and I’m a complete beginner. But let me try to answer your question.
Define the relationship in the model User. In my particular case it looks like this but it can also be different.
public function relations()
{
return array(
'jointUserCompany'=>array(self::HAS_MANY,'CompanyHasUser','user_id'),
'companies'=>array(self::HAS_MANY,'Company','company_id','through'=>'jointUserCompany'),
//instead you can use: 'companies' => array(self::MANY_MANY, 'Company', 'company_has_user(user_id, company_id)'),
);
}
Create a view associated with the controller User with a form and an input field
Now in a view associated with the controller user, the following outputs all companies associated with the user by using the name of the relation declared above
// loads all companies associated with the model User through the relation 'companies'
$companies=$model->companies;
// loops all companies by using the class $company declared in the model Company
foreach ($companies as $company)
{
// outputs db field name
echo $company->name;
}
We can restrict the companies to those who have company_has_user_role_id=1
Now let’s implement the whole thing with the form and with separating logic (controller) and display (view).
UserController:
public function actionShowCompanies()
{
// load all attributes and methods from db / model User
// by using the ID set in UserIdentity.php
$model = $this->loadModel(Yii::app()->user->id);
// when form is posted
if(isset($_POST['Company']))
{
// fetch posted value
$role = strip_tags($_POST['CompanyHasUser']['company_has_user_role_id']);
// display companies according to $role
if ( $role = 1 ) {
$this->render('sell',array(
'model'=>$model,
// only get companies that have role X and pass these on to the view
'companies'=>$model->companies(array('condition'=>'company_has_user_role_id=1'))
));
} else if ($role = 2) {
$this->render('sell',array(
'model'=>$model,
// only get companies that have role X and pass these on to the view
'companies'=>$model->companies(array('condition'=>'company_has_user_role_id=2'))
}
// if form has not been posted, display all companies associated with this user
} else {
$this->render('sell',array(
'model'=>$model,
'companies'=>$model->companies
));
}
In the view you can then use:
// loops all companies by using the class $company declared in the model Company
foreach ($companies as $company)
{
// outputs db field name
echo $company->name;
}
As I said, I’m just a beginner and this code has not been tested. So there are probably better ways to do this but hopefully it will give you a starting point.