0

I have 3 models

modelOne ( relation one to many ) modelTwo ( relation one to many ) model Three

In the third model there are columns with numbers, and I have created relation between second and third model to sum columns. Like this...

    public function getRelationTwoThree()
        {
            return $this->hasMany(modelThree::className(), ['modelTwo_id' => 'id'])
                        ->sum('m_1 + m_2');
        }

and that is ok. When I print second model instance like $modelTwo->relationTwoThree I get the right value.

How to create relationOneTwo between first and second model, to sum all the values of the relationTwoThree. I know that I can resolve this with foreach loop, but I want elegant and more correct way. Also to not slow the request.

Abizz
  • 216
  • 2
  • 16
tigrasti
  • 342
  • 3
  • 15

1 Answers1

0

The elegant solution I found is joinWith

public function getRelationOneTwo(){
     return $this->hasMany(modelTwo::className(), ['modelOne_id' => 'id'])
                        ->joinWith('relationTwoThree')
                        ->sum('m_1 + m_2');
}
tigrasti
  • 342
  • 3
  • 15