3

我有以下表格:

user (id, cv_personal_data_id),
cv_personal_data (id, firstname, surname, gender, address, ...),
cv_laboral_exp (id, user_id, position, seniority,... ),
cv_study (id, user_id, name, institution, average, ...),
cv_language (id, user_id, language_name, writing_level, ...)

在我的用户模型中,我定义了以下关系:

    public function relations()
{
    return array(
        'cvLaboralExps' => array(self::HAS_MANY, 'CvLaboralExp', 'user_id'),
        'cvLanguages' => array(self::HAS_MANY, 'CvLanguage', 'user_id'),
        'cvStudies' => array(self::HAS_MANY, 'CvStudy', 'user_id'),
        'cvPersonalData' => array(self::BELONGS_TO, 'CvPersonalData', 'cv_personal_data_id'),
}

问题是:作为公司登录,我需要显示一个列出所有用户的 CGridView,并能够通过相关表的任何字段进行搜索,例如“位置”(来自 cv_laboral_exp)、“语言名称”(来自cv_languages)等等。我似乎找不到搜索来自 HAS_MANY 关系的字段的解决方案。我尝试在 User 类的 search() 方法中将“with”语句添加到 $criteria 中,以尝试搜索用户劳动体验的位置,但没有成功:

                $criteria->compare('cvLaboralExps.position',$this->cvLaboralExps,true);
                $criteria->with = array('cvLaboralExps'=>array('select'=>'cvLaboralExps.position','together'=>true)); 

如您所见,有很多关系构成了用户的简历。如果有人能帮我解决这个问题,我将不胜感激,即使这意味着更改数据库/模型结构。

4

1 回答 1

5

您实际上需要为相关模型声明一个成员变量,这里是User。您正在做的问题是 this(in compare()) : $this->cvLaboralExps,这cvLaboralExps只是类的关系,而不是可以存储值的变量,因此比较$value是空的。$value比较文档中检查这一行,解释第二个参数:

如果字符串或数组为空,则不会修改现有的搜索条件。

这可以通过为模型声明一个成员变量并修改compare()调用以使用新变量来避免。

...
class User extends CActiveRecord{
    // declare the variables that we need
    public $cvLaboralExpsLocal,$cvLanguages,$cvStudies;

    // now put these variables in rules array, so that massive assignment can be done, i.e. safe rule
    public function rules(){
         return array(
              // other rules ...
              array('attributesxyz, cvLaboralExpsLocal, cvLanguages, cvStudies', 'safe', 'on'=>'search')
         );
    }

    // other functions

    // the search can be kept just the way you have in the question but with the new variables
    public function search(){
          // other statements
          $criteria->compare('cvLaboralExps.position',$this->cvLaboralExpsLocal,true);
          $criteria->with = array('cvLaboralExps'=>array('select'=>'cvLaboralExps.position','together'=>true));
    }
}

注意事项: 1. 记得更改 _search.php 表单以接受新变量。
2. 由于这是 has_many,因此您必须注意最终用户如何输入值。

于 2012-04-23T20:50:37.107 回答