To use the Active Record, you need to define the DB connection in one of the following ways:
Add the following code to the configuration file, for example, in config/common/bootstrap.php:
use Psr\Container\ContainerInterface;
use Yiisoft\Db\Connection\ConnectionProvider;
use Yiisoft\Db\Connection\ConnectionInterface;
return [
static function (ContainerInterface $container): void {
ConnectionProvider::set($container->get(ConnectionInterface::class));
}
];You can set the DB connection for Active Record using the DI container autowiring.
use Psr\Http\Message\ResponseInterface;
use Yiisoft\Db\Connection\ConnectionProvider;
use Yiisoft\Db\Connection\ConnectionInterface;
final class SomeController
{
public function someAction(ConnectionInterface $db): ResponseInterface
{
ConnectionProvider::set($db);
// ...
}
}Another way to define the DB connection for Active Record is to use dependency injection.
use Yiisoft\Db\Connection\ConnectionInterface;
class User extends ActiveRecord
{
public function __construct(private readonly ConnectionInterface $db)
{
}
public function db(): ConnectionInterface
{
return $this->db;
}
}/** @var \Yiisoft\Factory\Factory $factory */
$user = $factory->create(User::class);Back to README