abnab
abnab

Reputation: 846

Relationship issue in YII

I Have a GetStudents function in Agent model. where I fetch the students related to the agents.

But I want to show more fields of students from another table Eg

**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

I want to fetch householdname when I fetch all student details.

really looking bazzare to me as I am newbie to YII

MY function in agent model.

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,
)),
        ));
    } 

My code to fetch data in by passing ID into it

<?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',
    ),
)); ?>

Any help would be greatly appreicated.

Thanks Ab

Upvotes: 2

Views: 2327

Answers (1)

Owais Iqbal
Owais Iqbal

Reputation: 549

First you should make relation with student to relation table in relations array in relation model like this ..

'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

And then you can fetch all record with active record like this...

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

Upvotes: 2

Related Questions