apitin/database

Database

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

This package is auto-updated.

Last update: 2024-04-07 19:27:59 UTC


README

Database (PDO) extensions for apitin/apitin with query builder and ORM (as active record)

See https://github.com/wex/apitin-apitin to learn more.

Notice: master branch is still work in progress - only use stable releases!

Building query

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

How to define an active record

#[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)
  • If $timeStamps is true, you also need columns created_at and updated_at.
  • If $softDelete is true, you need column deleted_at.

Column()

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

Column types

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';

Create user

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

Read a single user (with PK=5)

$user = User::load(5);

Edit user (with PK=5)

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

Delete user (with PK=5)

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

Find single user

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

Find multiple users

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