|
我有以下表格:) ?8 s! r% U! l8 B" L
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,...)在我的用户模型中,我定义了以下关系:
! `2 [# u8 H) O0 Z: h5 m' W 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()方法中向$5 B$ |* M+ L/ P: H1 W
criteria添加’with’试图搜索用户辛苦工作的语句,但失败了:
+ E, m7 m% e" l3 Y $criteria->compare('cvLaboralExps.position',$this->cvLaboralExps,true); $criteria->with = array('cvLaboralExps'=>array('select'=>'cvLaboralExps.position','together'=>true));正如你所看到的,用户的简历有很多关系。如果有人能帮我解决这个问题,我会非常感激,即使这意味着改变数据库/模型结构。/ R. i- G0 H9 o
( ^# ]4 c1 z Y4 [7 u) |9 { 解决方案:
4 C9 w) m/ y/ ^+ p" i 事实上,你实际上需要为模型声明一个成员变量,这里是 User 。你正在做的问题是this(in
% S6 ?* c* `2 N) |7 hcompare())$this->cvLaboralExps:,这里cvLaboralExps只是类的关系,而不是可以存储值的变量,所以比较$value值为空。检查这行,$value解释比较文档中的第二个参数:
Y1 Q& R; l; D' ]- `若字符串或数组为空,则不会修改现有的搜索条件。, Z2 N, [( o. G2 v, a
可以为模型声明成员变量并修改compare()使用新变量来避免这种情况。. C8 b3 |1 J% s3 y; q) v
...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接受新变量的表单。
9 O9 {; I. Z& V; {8 Y0 b: R4 A2 T2.由于这是has_many,因此,您必须注意最终用户如何输入值。 |
|