Felipe Guzman
Felipe Guzman

Reputation: 55

How to use Distinct on a query with joins in Yii 2?

I need to write the next SQL query in a new search function from AsistenciaSearch:

SELECT DISTINCT asistencia.rutAlumno, alumno.nombreAlumno, planificacion.nombreSesion
FROM alumno, profesor, asistencia, planificacion
WHERE asistencia.rutAlumno = alumno.rutAlumno AND asistencia.idPlanificacion = planificacion.idPlanificacion AND profesor.escuelaProfesor = alumno.establecimientoAlumno AND profesor.rutProfesor = '11550308-1' 
GROUP BY asistencia.rutAlumno;

But because I need to show data from related tables on a view, I joined that tables in the search query. I try this query:

public function searchDistinctAlumno($params)
    {
        $query = Asistencia::find()->select('rutAlumno')->distinct()->count();

        // add conditions that should always apply here

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

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->joinWith('rutAlumno0');
        $query->joinWith('idPlanificacion0');

        // grid filtering conditions
        $query->andFilterWhere([
            'idAsistencia' => $this->idAsistencia,
            //'idPlanificacion' => $this->idPlanificacion,
        ]);

        $query->andFilterWhere(['like', 'asistencia', $this->asistencia])
            ->andFilterWhere(['like', 'alumno.nombreAlumno', $this->rutAlumno])
            ->andFilterWhere(['like', 'alumno.apellidoAlumno', $this->rutAlumno2])
            ->andFilterWhere(['like', 'alumno.establecimientoAlumno', Yii::$app->user->identity->escuelaProfesor])
            ->andFilterWhere(['like', 'planificacion.nombreSesion', $this->idPlanificacion]);

        return $dataProvider;
    }

But I get this error: Call to a member function joinWith() on string

I need help, please.

Upvotes: 1

Views: 710

Answers (1)

Bizley
Bizley

Reputation: 18021

Remove ->count() from the $query.

count() returns number of rows matching the query so you can not use it as Data Provider query anymore (because this variable is number now).

Upvotes: 1

Related Questions