nguyendh
(Duynguyen0511)
1
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();
grischer
(Alberto)
2
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
grischer
(Alberto)
4
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
nguyendh
(Duynguyen0511)
5
awesome, I use same technique. I guess all wise men think alike
thanks for sharing.