Relation In Model

for example i m having the 3 tables

  1. tab1 having 3 fields for primary members details




data like



  1. tab2 having 4 fields for secondary members details






data like





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





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…!!!


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.