Ljudotina
Ljudotina

Reputation: 279

Yii Grid View showing data from two models

I inherited job from colleague (he's sick) in Yii and i have to finish it. I never before worked with Yii and work has to be done today (lucky me).

In short, I need to create list that shows all users with user data. My problem is that part of data is not inside "users" table. There is "category" table that has ID and CATEGORY NAME in it and "users" table has "category" column with ID of category for that user. What i need in my list is category name, not id.

What I have now in my view is this:

    $dataProvider = $dataProvider=new CActiveDataProvider('users');
    $this->widget('bootstrap.widgets.TbExtendedGridView', array(
    'fixedHeader' => true,
    'headerOffset' => 40, // 40px is the height of the main navigation at bootstrap
    'type' => 'striped bordered condensed',
    'dataProvider' => $dataProvider,
    'responsiveTable' => true,
    'template' => "{pager}{summary}{items}{summary}{pager}",
    'columns' => array(
            'id',
            'username',
        ),
    ));

I need to add column "category" but i have no idea how to get category name from that table. I have 2 models. 1 model is users.php model which is pretty much empty:

class users extends CActiveRecord {
    public $dump;

    public static function model($className=__CLASS__) {
        return parent::model($className);
    }
}

and category model which has almost identical data:

class category extends CActiveRecord {
    public $dump;

    public static function model($className=__CLASS__) {
        return parent::model($className);
    }
 }

Is there way to get that data trough CActiveDataProvider or i have to hack it out manualy?

Upvotes: 1

Views: 1198

Answers (1)

gSorry
gSorry

Reputation: 1274

In Your users model you should have relations() method witch looks like this:

public function relations()
{
    return array(
        'category' => array(self::BELONGS_TO, 'category', 'category_id'),
    );
}

Then you can use it like this:

$user->category->name;

Upvotes: 1

Related Questions