Thursday, 18 December 2014

Relations in YII

In Inward.php (Inward model the method relations to be mapped to the related model as follows)

public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'refname'=>array(self::HAS_ONE,'RefMaster',array('id'=>'ref_code')),
            'reftname'=>array(self::HAS_ONE,'RefType',array('id'=>'ref_tcode')),
            'sub'=>array(self::HAS_ONE,'SubMaster',array('id'=>'sub_code')),
        );
    }

After defining the relation in views we can use as follows:

$this->widget('zii.widgets.CDetailView', array(
    'data'=>$model,
    'attributes'=>array(
        'ref_no',
        'section',
        'reftname.ref_tname',                  // relation name. Fieldname (The field name is ref_tname which belongs to RefType Model 

        'refname.ref_name',                   // ref_name is a field in RefMaster
        'apl_name',
        'sub.sub_name',
        'sub_desc',
        'pend_with',
        'reg_date',
    ),
)); ?>


Note : Please modify the attributeLabels as user readable in corresponding models in our case ref_name as 'Reference By' in the RefMaster model.

Example : RefMaster.php

public function attributeLabels()
    {
        return array(
            'ref_code' => 'Ref Code',
            'ref_name' => 'Reference By',
            'id' => 'ID',
        );
    }


So the view becomes more readable.

No comments:

Post a Comment