Struggling with RELATIONS

Can anyone suggest how to solve the following

I have the following relations

company  (id, ...)  

region   (id, company_id, ...) 

division (id, region_id, ...)

user     (id, division_id, ...)

A company has many regions, a region has many divisions and a division has many users.

Given a user, I want to find the company the user belongs to, so a simple sql query to find this would be

select company.* from company, region, division, user where = region.company_id 

AND = division.region_id AND = user.division_id AND = <img src='' class='bbc_emoticon' alt='???' />??;

HOWEVER what I need to know is:

Is it possible to define a relation in the User model to retrieve the related company.

Thus I can simply perform a query such as


If its not possible to define this with a relation could it be done with a model method?

Any help would be appreciated.


Configure the relations in the respective models like this:

user BELONGS_TO division

division BELONGS_TO region

region BELONGS_TO company

See the guide on AR relations for details.

Then you can fetch your data like this:


if ($user!==null)


Thanks Mike,

Got it to work by simply defining a method in the User model as follows, but really wanted to know if it could be done via a relation.

        public function getCompany()


           return Company::model()->findBySql(

                           'SELECT * from company,region,division,user 

                            WHERE = region.company_id 

                            AND = division.region_id 

                            AND = user.division_id 

                            AND = :id',array(':id'=>$this->id)



PS. In your example the order of the with tables doesn’t work as user doesn’t have a region relation. So needs to be