apitin/database

数据库

v1.1.0 2023-10-19 22:31 UTC

This package is auto-updated.

Last update: 2024-09-07 20:29:19 UTC


README

apitin/apitin 提供数据库 (PDO) 扩展,包括查询构建器和 ORM(作为活动记录)

要了解更多信息,请访问 https://github.com/wex/apitin-apitin

注意:master 分支仍在开发中 - 只使用稳定版本!

构建查询

$users = new Apitin\Database\Select('users');
$users->where('is_active = ?', 1);
echo count($users->all()) . PHP_EOL;

如何定义活动记录

#[Table("users")]
#[Column("name")]
#[Column("logged_at", type: Column::TYPE_DATETIME)]
class User extends Apitin\Database\Record
{

}

Table()

Table(string $tableName, string $primaryKey = 'id', bool $timeStamps = false, bool $softDelete = false)
  • 如果 $timeStamps 为 true,则需要 created_atupdated_at 列。
  • 如果 $softDelete 为 true,则需要 deleted_at 列。

Column()

Column(string $name, string $type = Column::TYPE_STRING, bool $required = false, mixed $default = null)

列类型

const   TYPE_STRING     = 'string';
const   TYPE_INTEGER    = 'int';
const   TYPE_DECIMAL    = 'decimal';
// Converted to/from boolean <-> int
const   TYPE_BOOLEAN    = 'bool';
// Converted to/from DateTimeImmutable
const   TYPE_DATETIME   = 'datetime';
// Converted to/from DateTimeImmutable
const   TYPE_DATE       = 'date';

创建用户

$user = User::create([
    'name'  => 'Test User',
]);
$user->save();

读取单个用户(PK=5)

$user = User::load(5);

编辑用户(PK=5)

$user = User::load(5);
$user->name = 'Updated Test User';
$user->save();

删除用户(PK=5)

$user = User::load(5);
$user->destroy();

查找单个用户

$user = User::select()->where('name = ?', 'Test User')->first();

查找多个用户

$select = User::select()->where('id > 6');
$users = $select->all();
echo count($users) . PHP_EOL;