Active Query Question

I saw the Yii3 progress at 95% today so I figured I’d give it a try. I was able to get the app running with MySQL and ActiveRecord.

As it stands right now I have to make a database call like this

$userQuery = new ActiveQuery(User::class);
$userQuery->where(['id'=>1])->one();

Instead of something simpler like

User::where(['id'=>1])->one()

I’m assuming this will be updated sometime before 100% is hit, can someone confirm?

You could create a trait handling that task for you.

<?php

declare(strict_types=1);

namespace App;

use DomainException;
use Yiisoft\ActiveRecord\ActiveQuery;

trait ActiveRecordQueryTrait
{
    /**
     * Returns an {@link ActiveQuery} instance for the (sub-)class using this trait.
     *
     * @param string|null $class the FQDN for which to create the query instance
     *
     * @return ActiveQuery
     */
    public static function query(?string $class = null): ActiveQuery
    {
        $class ??= static::class;
        if (!is_a($class, __CLASS__, true)) {
            throw new DomainException("Class '$class' is not a subclass of " . __CLASS__);
        }

        return new ActiveQuery($class);
    }
}

Then in your user active-record class, use the trait like this:

<?php

declare(strict_types=1);

namespace App;

use Yiisoft\ActiveRecord\ActiveRecord;
use Yiisoft\ActiveRecord\ActiveRecordInterface;

/**
 * Entity User.
 *
 * Database fields:
 *
 * @property int    $id
 **/
class User extends ActiveRecord
{
    use ActiveRecordQueryTrait;

    public function getTableName(): string
    {
        return '{{%user}}';
    }

    /**
     * Query database for given user ID
     *
     * @param int $id
     *
     * @return ActiveRecordInterface|null
     * @throws \ReflectionException
     * @throws \Throwable
     * @throws \Yiisoft\Db\Exception\Exception
     * @throws \Yiisoft\Db\Exception\InvalidArgumentException
     * @throws \Yiisoft\Db\Exception\InvalidConfigException
     * @throws \Yiisoft\Db\Exception\NotSupportedException
     */
    public static function findByPk(int $id): ?ActiveRecordInterface
    {
        return static::query()->where(['id' => $id])->one();
    }
}

This is untested but may work.

Reason for the trait is:

  1. Flexibility in which class you want to use it
  2. Parametrized query() method accepts a “$class” parameter which must be either match the class using the trait or be a subclass of it
  3. The static::query()->where([‘id’ => $id])->one(); will ensure that you will get instances of the class calling findByPk()