Yii2 gridView Sort last record from a hasMany relation

179 Views Asked by At

I'm trying use a sort (in header of gridView) by 'id_state'last record from a hasMany relation, and the sort not apply correctly.

tables:

formation

id, name

formation_registration

id, id_formation, id_user

formation_registration_steps

id, id_formation_registration, id_state

Im trying to get that last state row with a relation in yii2 as follows:

formationRegistration model:

public function getFormationRegistrationSteps()
    {
        return $this->hasMany(FormationRegistrationSteps::className(), ['id_formation_registration' => 'id']);
    }


    public function getFormationRegistrationStepsLast()
    {
        return $this->hasOne(FormationRegistrationSteps::className(), ['id_formation_registration' => 'id'])
            ->orderBy(['id' => SORT_DESC]);
    }

formationRegistrationSearch model:

public function search($params)
    {
        $query = FormationRegistration::find();

        // add conditions that should always apply here
        $query->joinWith('formationRegistrationStepsLast lastStep');

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $dataProvider->setSort([
            'attributes' => [
                'lastStep.id_state' => [
                    'asc' => ['lastStep.id_state' => SORT_ASC],
                    'desc' => ['lastStep.id_state' => SORT_DESC],
                ],
            ],
        ]);

        //(..)
    }

gridView

(..)
['attribute' => 'lastStep.id_state',
'format' => 'raw',
'value' => function ($model) {
 if(isset($model->formationRegistrationSteps->id_sate))
   return $model->formationRegistrationSteps->id_sate;
 }
],
(..)
0

There are 0 best solutions below