2012-05-15 65 views
1

我在Agent模型中有一个GetStudents函数。在那里我找到与代理有关的学生。YII中的关系问题

但我想向学生展示的更多的字段从另一个表 如

**Agent table** (agent has students) 
agent_id 

**student table** 
STUDENTID pkey 
agent_id 

**relation table** (this table creates relation between student and household) 
StudentID HOUSEHOLDID 

**HOUSEHOLD TABLE** 
HouseHOLDID Householdname 

我想,当我获取所有学生的信息获取householdname。

真的希望bazzare给我,我新手警予

我的代理模式的功能。

public static function getStudents($id) { 
     $relationships = Relationship::model()->findAll('type = :type AND source = :agent_id', array(':type' => 2, ':agent_id' => $id)); 
     //$relationships=sort($relationships); 
     // Generate relationship array 

     //print_r($relationships); 
     foreach ($relationships as $relationship) { 
      $in[] = $relationship->destination; 
     } 

     // Generate db condition 
     $criteria = new CDbCriteria; 
     if (! isset($in) || ! is_array($in) || sizeOf($in) == 0) { 
      $in[] = -999; 
     } 
     $criteria->addInCondition('StudentID', $in, 'OR'); 



     return new CActiveDataProvider('Student', array(
      'criteria' => $criteria, 
      'sort'=>array('defaultOrder'=>array(
    'StudentID'=>CSort::SORT_DESC, 
)), 
     )); 
    } 

我的代码在通过传递ID进去

<?php $this->widget('zii.widgets.CDetailView', array(
    'data' => $model, 
    'attributes' => array(
array(
    'label' => 'Agent Details', 
    'type' => 'raw', 
    'value' => '', 
    'cssClass' => 'heading', 
), 
'agent_id', 
'user.email', 
'first_name', 
'last_name', 
'company', 
'phone', 
    ), 
)); ?> 

任何帮助将大大appreicated获取数据。

感谢 抗体

回答

2

首先,您应与学生关系表关系在relations阵列relation model这样的..

'student'=>array(self::BELONGS_TO, 'Student', 'StudentID'), //after belongs to student is model class name 

'household'=>array(self::BELONGS_TO, 'HOUSEHOLD', 'HOUSEHOLDID'),//after belongs to HOUSEHOLD is model class name 

然后你就可以获取像这样的活动记录的所有记录。 ..

$relationships = Relationship::model()->with('student','household')->findAll('type = :type AND source = :agent_id', array(':type' => 2, ':agent_id' => $id)); 
+0

嗨感谢您的快速回复..但关系表在哪里使用?我有一个与 StudentID HOUSEHOLDID字段的关系表,它使学生和家庭之间发生关系。 再次感谢 ab – abnab

+0

关系是你的模型和('学生','家庭')与关系模型建立关系..在这里你的关系使用.. –

+0

关系“学生”没有定义在活动记录类“关系”。 (''''''''>''),以及'(''''''''') - > findAll('type =:type AND source =:agent_id' 2,':agent_id'=> $ id)); \t \t ' ' 公共函数关系(){ \t \t返回阵列( \t \t \t '用户'=>数组(自:: HAS_ONE, '用户', 'USER_ID'), \t \t“学生'=> array(self :: BELONGS_TO,'Student','StudentID'), 'household'=> array(self :: BELONGS_TO,'Household','HouseholdID'), ); \t}' – abnab