Relation In Model

for example i m having the 3 tables

  1. tab1 having 3 fields for primary members details

----tab1_id(PK)

----fname

----lname

data like

1-----test_firstname------test_lastname<br/>

2-----test2_firstname------test2_lastname

  1. tab2 having 4 fields for secondary members details

----tab2_id(PK)

----fname

----lname

----tab1_id(FK)

----count

data like

1----test1_firstname-----test1_lastname-----1-----1<br/>

2----test2_firstname-----test2_lastname-----1-----2<br/>

3----test1_firstname-----test1_lastname-----2-----1<br/>

and

  1. tab_data having combine details of the primary and secondary based upon the flag count field

----tab_data_id

----operation

----tab1_id(FK)

----count(FK)

now how i can write the conditional relation for the tab_data model class

i want to if count==0 then self belogns to tab1 using tab1_id field and if count>0 then self belogns to tab2 using tab1_id and count filed…

is it posssible in YII…!!!

thanks.

In Yii-2, the table relations are defined as get functions in which you return hasMany or hasOne in the AR model. Read the guides, you could be able to do this.

You could try something like this in your TabData model (I assume you have 3 models Tab1, Tab2, and TabData):




// TabData model

public function getDetails() {

   $status = ($this->count == 0) ? true : false; 

   if ($status) {

      return $this->hasOne(Tab1::className(), ['tab1_id' => 'tab1_id']);

   }

   else {

      return $this->hasOne(Tab2::className(), ['tab1_id' => 'tab1_id', 'count' => 'count']);

   }

}



You can use then $model->details for the relation. I am not sure of the syntax for composite key passing, but check the docs and see.