This package provides ActiveRecord library. It is used in Yii Framework but is supposed to be usable separately.
Packages | Versions | CI-Actions |
---|---|---|
[db-mssql] | 2017 - 2022 | |
[db-mysql] | 5.7 - 8.0 | |
[db-oracle] | 11 - 21 | |
[db-pgsql] | 9.0 - 15.0 | |
[db-sqlite] | 3:latest |
- PHP 8.1 or higher.
The package could be installed with Composer:
composer require yiisoft/active-record
Note: You must install the repository of the implementation to use.
Example:
composer require yiisoft/db-sqlite
Add the following code to the configuration files, for example:
config/common/di/db.php
:
use Yiisoft\Db\Connection\ConnectionInterface;
use Yiisoft\Db\Sqlite\Connection;
use Yiisoft\Db\Sqlite\Driver;
return [
ConnectionInterface::class => [
'class' => Connection::class,
'__construct()' => [
'driver' => new Driver($params['yiisoft/db-sqlite']['dsn']),
],
]
];
config/common/params.php
:
return [
'yiisoft/db-sqlite' => [
'dsn' => 'sqlite:' . dirname(__DIR__) . '/runtime/yiitest.sq3',
]
]
For more information about how to configure the connection, follow Yii Database.
config/common/bootstrap.php
:
use Psr\Container\ContainerInterface;
use Yiisoft\ActiveRecord\ConnectionProvider;
use Yiisoft\Db\Connection\ConnectionInterface;
return [
static function (ContainerInterface $container): void {
ConnectionProvider::set($container->get(ConnectionInterface::class));
}
];
See other ways to define the DB connection for Active Record.
use Yiisoft\ActiveRecord\ActiveRecord;
/**
* Entity User.
*
* Database fields:
* @property int $id
* @property string $username
* @property string $email
**/
#[\AllowDynamicProperties]
final class User extends ActiveRecord
{
public function getTableName(): string
{
return '{{%user}}';
}
}
For more information, follow Create Active Record Model.
Now you can use the Active Record:
use App\Entity\User;
$user = new User();
$user->set('username', 'yiiliveext');
$user->set('email', '[email protected]');
$user->save();
Usage with ActiveQuery
:
use App\Entity\User;
use Yiisoft\ActiveRecord\ActiveQuery;
$userQuery = new ActiveQuery(User::class);
$user = $userQuery->where(['id' => 1])->one();
$username = $user->get('username');
$email = $user->get('email');
If you need help or have a question, the Yii Forum is a good place for that. You may also check out other Yii Community Resources.
The Yii Active Record Library is free software. It is released under the terms of the BSD License.
Please see LICENSE
for more information.
Maintained by Yii Software.