AR relation chaining

Hi, is it possible to chain database table relations within the zii.CGridView?

The first table has an id that I can connect with the second table, and with that data I want to connect to the third table. Is that possible?

my relation looks like this:

‘swimmer’ => array(self::BELONGS_TO, ‘Swimmer’, ‘swimmer_id’),

In the zii.widgets.grid.CGridView I can access this(the second table) using swimmer.swim_club_id.

With the swim_club_id, I want to grab the name that matches that id within the Clubstable(the third table).

Thanks in advance!

If the relations among 3 tables are defined as:

// in ModelA.php

'swimmer' => array(self::BELONGS_TO, 'Swimmer', 'swimmer_id'),


// in Swimmer.php

'swim_club' => array(self::BELONGS_TO, 'SwimClub', 'swim_club_id'),


And when SwimClub has an attribute named ‘club_name’, then you can access it like:

$model = ModelA::model()->findByPk($id);

$club_name = $model->swimmer->swim_club->club_name;

Or, in CGridView …

    'columns' => array(



            'header' => 'Club Name',

            'value' => '$data->swimmer->swim_club->club_name',



In the CGridView. When i call $data->swimmer->swim_club->club_name, I get an error saying :

"Trying to get property of non-object"

If I replace $data with $model it says it is undefined. What should I replace $data with?

My widget looks like this now:

<?php $this->widget('zii.widgets.grid.CGridView', array(












            'header' => 'Club Name',

            'value' => '$data->swimmer->swim_club->club_name',











)); ?>

My code is just a sample to illustrate how relations work.

I don’t know what you really have for your swim club model. You have to replace some model names, relation names and attribute names according to your code. :)

Probably the relation name ‘swim_club’ is wrong.

Thanks for the help! Solved it

You become a bit lazy when the forum is so good :)

You should post your solution for the benefit of others.