C
C
Crash2018-06-19 11:39:11
Yii
Crash, 2018-06-19 11:39:11

Why is ActiveQuery needed in Yii2?

I have been working with Yii2 for more than 3 years, all this time I managed exclusively with ActiveRecord. But there is also ActiveQuery, but even hands never reached it.
Why exactly is this class needed?
To be more specific, why is this option needed when generating a model through Gii?
5b28c652d8b06395601887.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Fedorov, 2018-06-19
@Bandicoot

To be more specific, why is this option needed when generating a model through Gii?
So that you can add your custom methods or override native ones (all(), one() and others, in short, override native ActiveQuery and change to your own abstractions)
Here is an example of a controller:
Ну раз нужен -- добавляем такой метод
class TrainingQuery extends \yii\db\ActiveQuery
{
    public function actual($date)
    {
        return
            $this->alias('t')
            ->joinWith(['lesson l' => function($q){
                $q->joinWith('studio s');
            }])
            ->andWhere(['l.active' => 1])
            ->andWhere(['s.active' => 1])
            ->andWhere(['t.date' => $date])
            ->all();
    }
}

В сущности перенацеливаем родной find() на мой кастомный
class Training extends \yii\db\ActiveRecord
{
...
public static function find()
    {
        return new \mynamespace\entities\query\TrainingQuery(get_called_class());
    }

S
SwoDs, 2018-06-19
@SwoDs

I'll tell you a secret, ActiveRecord uses ActiveQuery, you can get more complete information by studying the documentation and the guide (for 3 years you could have read it) =)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question