Search code examples
phpyii2yii2-advanced-appyii2-model

Sum on the multiple relations between models


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.


Solution

  • 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');
    }