Filtering in index view

I have models Section, Course, Term, Categories (and others).

A Section is a particular Course in a particular Term.

Categories belong to a section.

So, on my categories index view I wish to filter by a particular term and/or course.

My CategorySearch Model (removed unnecessary code)

public function rules()


        return [

            [['category_id', 'section_id', 'category_weight', 'category_ord'], 'integer'],

            [['category_name', 'section','term', 'course'], 'safe'],



    public function search($params)


        $session = Yii::$app->session;

        $query = Category::find()


                ->where(['course.teacher_id' => $session['user.user_id']])

                ->andWhere(['course.school_year_id' => $session['schoolYears.currentSchoolYear']])



        $dataProvider = new ActiveDataProvider([

            'query' => $query,


        $dataProvider->sort->attributes['course'] = [

            'asc' => ['section.course.course_name' => SORT_ASC],

			'desc' => ['section.course.course_name' => SORT_DESC],


        $dataProvider->sort->attributes['term'] = [

            'asc' => ['section.term.term_name' => SORT_ASC],

            'desc' => ['section.term.term_name' => SORT_DESC],



        if (!$this->validate()) {

            // uncomment the following line if you do not want to any records when validation fails

            // $query->where('0=1');

            return $dataProvider;



            'category_id' => $this->category_id,

            'section_id' => $this->section_id,

            'category_weight' => $this->category_weight,

            'category_ord' => $this->category_ord,


        $query->andFilterWhere(['like', 'category_name', $this->category_name])

                ->andFilterWhere(['like','course.course_name', $this->section]);

        return $dataProvider;


I can’t wrap my head around how to get the nested relations in the filter to work. Any help would be appreciated.


This helped me to get related search working:

Or you can read my post here:

at the beginning of the post (inside the spoiler) I basically posted everything needed to do related search.

Hope this helps!


Thanks MetaCrawler

Problem is on the categories Model, I don’t have a relation to Term or Course, only to Section. Then Section has a relation to Term and Course

I already have the filtering working with direct relations.