UFFAN AHMED
UFFAN AHMED

Reputation: 674

How to show the data from foreign key in case of different column name in CDetailView Yii

How to show the data from foreign key in case of different column name in CDetailView Yii

Table1

x1      x2
1       sample text 1
2       sample text 2
3       sample text 3

Table2

y1      y2          y3 (foreign key x1)
1       text 1      1
2       text 2      1
3       text 3      2

I want to show the following result

y1      y2          y3
1       text 1      sample text 1
2       text 2      sample text 1
3       text 3      sample text 2

This is relation Code in Model Class

public function relations(){
    return array(
         'Table2' => array(self::BELONGS_TO, 'Table1', array('x1'=>'y3'))
    );
}

This is my CDetailView Code

<?php $this->widget('zii.widgets.CDetailView', array(
    'data'=>$model,
    'attributes'=>array(
         array(
             'name'=>'Table2.y3',
             'value'=>$model->Table2->x2,
         ),
         'y1',
         'y2'
    ),
)); ?>

I am getting the following Error

Property "Table2.x1" is not defined. 

Upvotes: 0

Views: 256

Answers (1)

Rajat Singhal
Rajat Singhal

Reputation: 11264

First problem: the relations are not defined properly (as far as I can understand from the info provided)

Relations in model of Table1

public function relations(){
    return array(
         'Table2' => array(self::HAS_MANY, 'Table2', 'y3')
    );
}

As one object of table1's model will have many table2's objects

Relations in model of Table1

public function relations(){
    return array(
         'Table1' => array(self::BELONGS_TO, 'Table1', 'y3')
    );
}

As one object of table2's model belongs to some table's object..

Now after defining the relations properly you can use 'value'=>$data->Table2->x2, to print value from the relation..

Upvotes: 0

Related Questions