0

在我的项目中的一个视图中,我需要显示使用来自两个表的数据的表,但其中一个是连接表。

我有两张表UserSkill。这两者之间的关系是多对多的,所以我创建了联结表StudentSkills

这个联结表不仅像往常一样具有id_userid_skill,而且还具有对于给定的一对 id 唯一的百分比值 - 这就是为什么它在联结表中的原因,即使您不应该将其他任何东西放在那里作为一个好的做法。

在视图中的所述表中,我需要显示包含来自技能表的名称和来自证书用户的StudentSkills联结表的百分比的行。

这是我的看法:

<?php 
    $this->widget('zii.widgets.grid.CGridView', array(
        'id'=>'skills-grid',
        'dataProvider'=>$model->with('student_skills')->searchWithStudentId($id),
        'template' => '{items}{pager}',
        'cssFile'=>Yii::app()->request->baseUrl. '/themes/'. Yii::app()->theme->name.'/css/table.css',
        'htmlOptions'=>array('class'=>'datagrid', 'style'=>'width:550px;'),
        'columns'=>array(
            array(
                'name'=>Yii::t('MainTrans', 'Name'),
                'value' => '$data->name',
                                        ),
            array(
                'name'=>'percentage',
                'header' => Yii::t('MainTrans', 'Success rate %'),
                'value' => '$data->student_skills->percentage',
                 ),
            ),
    ));

?>

这是我在 Skill $model 中的搜索和关系:

public function relations()
{
    return array(
        //the first two relations were generated by gii
        'problems' => array(self::MANY_MANY, 'Problems', 'problem_skill(id_skill, id_problem)'),
        'users' => array(self::MANY_MANY, 'User', 'student_skills(skill_id, student_id)'),

        //this is what tired to do
        'student_skills' => array(self::HAS_MANY, 'StudentSkills', 'skill_id'),
    );
}

public function searchWithStudentId($studentId)
{
    // my custom search to find all records with certain user_id

    $criteria=new CDbCriteria;

    $criteria->compare('id',$this->id);
    $criteria->compare('name',$this->name,true);

    $criteria->with = array('student_skills');
    $criteria->together = true;

    $criteria->compare('student_skills.student_id',$studentId);

    return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
            'pagination'=>array(
                    'pageSize'=>25,
            ),
            'sort'=>array(
                    'defaultOrder'=>array(
                            'title'=>CSort::SORT_ASC
                    )
            ),
    ));
}

当我尝试渲染页面时出现错误:Trying to get property of non-object

我知道我的代码有问题,很可能与关系有关,但我找不到任何东西。

有人可以帮助解决这个问题而不必创建新表吗?

谢谢

4

1 回答 1

0

问题是您正在使用HAS_MANY关系,这意味着每个Skill模型都有超过1 StudentSkill。你得到一个数组student_skills,所以你需要用它做点什么。例如获取数组中的第一个百分比

$data->student_skills[0]->percentage

或计算给定技能的平均百分比

array_sum($data->student_skills)/count($data->student_skills)
于 2014-09-19T09:45:00.953 回答