P
P
Pogran2016-07-05 21:47:14
Yii
Pogran, 2016-07-05 21:47:14

How to properly use ActiveQuery extending ActiveRecord?

I have a User class that inherits from ActiveRecord
In this class, I extend the find method like this

public static function find()
    {
        return new UserQuery(get_called_class());
    }

and here is the UserQuery class itself
class UserQuery extends ActiveQuery
{
    /**
     * @param $role integer
     * @return $this
     */
    public function forRole($role) 
    {
        return $this->andWhere(['role' => $role]);    
    }
}

And now I want to get a list of users for grida (just for the filter) that are Providers.
I do it like this
User::find()->select(['username','id'])->forRole(User::ROLE_PROVIDER)->indexBy('id')->column()

the question is whether this record is good, or in the form it is necessary to somehow use the capabilities of the models (ActiveQuery) more and call some thread function UserQuery::UsersByRole(User::ROLE_PROVIDER)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Shilov, 2016-07-05
@Dry7

It's better to make a getUserProviders method in the User class, and put your selection code there.
This is more correct, because this selection can be used in many places, and if it needs to be changed, it is easier to do it in one place than to climb around the entire project.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question