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