Search code examples
yii2dataprovider

Custom Data Provider using foreach yii2


I'm trying to create a custom dataProvider made out of Professor's id’s (teachers id’s). My site hosts information about teachers, courses, grades, etc. for schools.

ER model

The user Alumno (student) will see a gridview of it’s professors for each course he’s registered in, so, I’m trying to return that information in a dataProvider.

First, I ask if the user is an Alumno.

Then I search for the Asignaturas the Alumno is registered in.

With that information, I search for the professors that teaches that Cursos, to return it’s id’s as a dataProvider, so I made a foreach cycle.

What I need is an array of Profesores id’s so I can show Profesors’s names in the grid view. The actual code is querying the last Profesor id into the dataProvider.

public function actionIndex()
{        
    $this->layout = 'main';
    $searchModel = new ProfesorSearch();

    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

    if(User::isUserAlumno(Yii::$app->user->identity->id)){
        $alumno = Alumno::find()->where(['id_usuario' => Yii::$app->user->identity->id])->one();
        $asignaturas = Asignatura::find()->where(['id_curso' => $alumno->id_curso])->all();
        foreach ($asignaturas as $asignatura){
            $dataProvider = new ActiveDataProvider([
            'query' => Profesor::find()->where(['id' => $asignatura->id_profesor])
            ]);
        }
    }

    return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
    ]);
}

Any help would be appreciated.


Solution

  • You can use column() to get all id_profesor from query.

    $profesorIds = Asignatura::find()->select('id_profesor')->where(['id_curso' => $alumno->id_curso])->column();
    
    $dataProvider = new ActiveDataProvider([
       'query' => Profesor::find()->where(['id' => $profesorIds])
    ]);