reuse active record code

I use the below code in several different place. what is the best way to refactor it ? put it inside a static function in a model ?





$employeePayRate =

    EmployeePayRate::find()

        ->select(['{{employee_pay_rate}}.*, CONCAT( {{project}}.name, \' \', {{classification}}.short_code ) as name'])

        ->joinWith('project', false, 'INNER JOIN')

        ->joinWith('classification', false, 'INNER JOIN')

        ->where(['project_id' => $projectId, 'status' => EmployeePayRate::STATUS_ACTIVE])

        ->asArray()->all();




Yes usually i create a function in the model so it is always accessible when I call the model

Yes I also would do something like this…

In your EmployeePayRate Model:

(No tested code - just for example)




public static function myModelFunction($projectId)

{


    return static::find()

        ->select(['{{employee_pay_rate}}.*, CONCAT( {{project}}.name, \' \', {{classification}}.short_code ) as name'])

        ->joinWith('project', false, 'INNER JOIN')

        ->joinWith('classification', false, 'INNER JOIN')

        ->where(['project_id' => $projectId, 'status' => EmployeePayRate::STATUS_ACTIVE])

        ->asArray()->all();

}




And call it for example in controller like:




$myWantedResult = EmployeePayRate::myModelFunction();



Not sure if this is the "best" practise,

but at least you have a single point where to find and edit this code across the whole app.

Regards

I usually use this type of code:




 

public static function($projectId){

$employeePayRate = EmployeePayRate::find()

        ->select(['{{employee_pay_rate}}.*, CONCAT( {{project}}.name, \' \',             {{classification}}.short_code ) as name'])

        ->joinWith('project', false, 'INNER JOIN')

        ->joinWith('classification', false, 'INNER JOIN')

        ->where(['project_id' => $projectId, 'status' => EmployeePayRate::STATUS_ACTIVE])

        ->all();

return $employeePayRate;

}



Just another way to write the same thing :D

awesome, I use same technique. I guess all wise men think alike :)

thanks for sharing.