0

For example there are A, B, C, D, E, F tables.

A has a_id as foreign key in B. B has a_id and c_id as foreign key. C has d_id as foreign key. D has e_id as foreign key.

Now how do I write a relation from A to D. As A has no direct relation to D.

From A to C I write the relation as below.

    public function C
{
   return $this->hasMany(C::className(), ['c_id' => 'c_id'])
            ->via('B');
}

How do i get through relations from A to D?? I cannot find the syntax anywhere online.. Thanks..

Mohan Prasad
  • 682
  • 1
  • 9
  • 34

1 Answers1

0

I had similar problem when I started with yii2 from A you have to have relation to B, from B to C and from C to D connection , like this on all models. So the function will look like this in A it will look like this( I added in A model main ID wich is id_A):

public function B
{
   return $this->hasMany(B::className(), ['a_id' => 'id_A'])

}

The same will be for B to C, in model B you have:

public function C
    {
       return $this->hasMany(C::className(), ['id_C' => 'c_id'])

    }

Remember this connection C::className(), ['id_C' => 'c_id'] is from column from next model you need to this model where you are, data have to be related. After this you need to set app the search model for the main model( A ). The search have to look like this. First you add the in A search model:

public $id_C
Public $c_id ...

all variables which you will add from other models. And after this add them in firs row in

public function rules()
    {
        return [
           [[......, 'id_C','c_id'...(all var you need)  ]] 
          .....] }

After you add all of them in first row(it will make them safe) go to

public function search($params)
    { $query = A::find()
      ->select(...)
      ->where (...)
      ->joinWith(B)->joinWith(A.B)->joinWith(A.B.C).... how many you need.
      ;
Alexei
  • 119
  • 17