1
votes

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?

1
Did you create that classes manually? Because some code is missing in it... You can use gii module to generate models based on database tables: yiiframework.com/doc/guide/1.1/en/topics.gii - gSorry
I'm afraid this is what i found it. Listing users from "users" table works nice and without of any errors. I can list "category" id's b simply adding "category" column inside view. but i dont need it's id, i need it's name that is stored in another table. - Ljudotina
Hey, Category is related with user? If so you need to add a relation in both models, and then do a custom method in users like getUsersWithCategory() which returns a CActiveDataProvider with with('categories') keyword to eager load the categories. Then in the view you just display $user->category - JorgeeFG
Look at the manual on Relations and also see this: yiiframework.com/wiki/181/relations-belongs_to-versus-has_one - JorgeeFG

1 Answers

1
votes

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;