Need help with custom method in model

I have a model for Sections that I created a method

    public static function getTeacherSectionList()


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

        $query = Section::find();




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

        $query->orderBy('term.term_name, course.is_core desc, course.course_name');

        return $query;


and in my SectionSearch model I call it like this…

$query = Section::getTeacherSectionList();

I did this because I will need to retrieve the teachers Sections frequently. My question is, from another page, like assignments, if I wish to put a dropdownList on my assignments index.php view and select a section before displaying the assignments, how do I call the getTeacherSectionList() properly. That method returns a query but I need to execute the query (verified with var_dump).

Hi jujubee:

The correct way to do this is to put that custom query in an ActiveQuery sub-class. So for example you’d do something like this:

class Sections extends \yii\db\ActiveRecord


    public static function find()


     	return new SectionsQuery(get_called_class());



//And then in the SectionsQuery it would look something like this:

use yii\db\ActiveQuery;

use Yii;

class SectionsQuery extends ActiveQuery


    public function teacherSectionList()


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


        return $this->joinWith('term'),



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

			->orderBy('term.term_name, course.is_core desc, course.course_name');



And then you’d use it this way:



C Hodges, thanks for the reply. So where is a good location to store this custom class? Models folder since they interact with db?

So I have my dropdownlist…

In my index.php view for Categories I have…

$section = new Section();

$sections = Section::find2()->teacherSectionList()->all();

foreach($sections as $s){

    $sectionList[] = ['section_id'=>$s->section_id,'course_name'=>$s->term['term_name']."-".$s->course['course_name']];


AND to make the dropdownlist I have…

<?= Html::activeDropDownList($section, 'section_id',

      ArrayHelper::map($sectionList, 'section_id', 'course_name')) ?>

Is this correct?

Yes I’d keep it right in the models folder.

And yes that code you have looks fine. I do it a little differently but your way is fine too!