How To Merge Two Lists Of Data

I need to create a list of users and roles.

I can get users with


$users =  User::model->findAll()   or  CHtml::listData(User::model()->findAll(), 'id', 'username');

and roles with


 $roles =  Role::model->findAll()   or  CHtml::listData(Role::model()->findAll(), 'id', 'role');

Is it possible to combine them?

I can do this in SQL using




select id, 0, role from role 

union

select role_id, id, displayname from user 

order by 1, 2;

I thought about a view to merge data - but having 3 fields role_id, id as a key and name/role - not sure I can do this with lists.




create view user_role as

select id, 0, role from role 

union

select role_id, id , displayname from user 

order by 1, 2;

I need to have a dropdownlist for the user to select either a role or a user to assign a task. It’s a pretty simple problem

but I can’t seem to get my head around it in the framework.

Thanks!

Assuming you’ve created a method in the user and role models to make the ID’s of the two models distinguishable:




    public function getDistinguishableId() // Come up with a better name here =)

    {

        return 'u' . $this->id; // or 'r' for role

    }



then you could do something like this:




    CHtml::dropDownList('name', 'value', array(

        'Users'=>CHtml::listData(User::model()->findAll(), 'distinguishableId', 'username'),

        'Roles'=>CHtml::listData(Role::model()->findAll(), 'distinguishableId', 'role'),

    ));



You’re going to have a bit of extra work in processing the data, but it shouldn’t be too difficult.