Search by

drago-ex / database

accgit

Connecting to database for Nette Framework

Package info

github.com/drago-ex/database

pkg:composer/drago-ex/database

Statistics

Installs: 6 346

Dependents: 8

Suggesters: 0

Stars: 1

Open Issues: 0

v3.0.9 2026-10-17 13:16 UTC

README

English | Čeština

Simple database helpers built on top of Dibi.

License: MIT PHP version Tests Coding Style

Requirements

  • PHP >= 8.3, < 9
  • Nette Framework
  • dibi
  • Composer

Installation

composer require drago-ex/database

Knowledge

Basic Model Example

A model uses the Database trait and describes its table with the Table attribute (table name and primary key). The trait reads the connection from the $connection property:

use Dibi\Connection;
use Drago\Attr\Table;
use Drago\Database\Database;

#[Table('table_name', 'id')]
class Model
{
	use Database;

	public function __construct(
		protected Connection $connection,
	) {
	}
}

Common Queries

The query methods return a query builder (ExtraFluent). Fetch the result with record() or recordAll(), or run a write query with execute():

// All records
$rows = $this->model->read('*')->recordAll();

// Records by column value
$rows = $this->model->find('column', 'value')->recordAll();

// One page of records
$rows = $this->model->read('*')->limit(10)->offset(20)->recordAll();

// One record by the primary key, or null
$row = $this->model->get(1)->record();

// Delete records by column value
$this->model->delete('column', 'value')->execute();

Without an entity class, records are returned as Dibi\Row objects.

Save a record as an array. When the array contains the primary key with a value greater than zero, the record is updated, otherwise a new record is inserted:

$this->model->save(['column' => 'value']);
$this->model->save(['id' => 1, 'column' => 'value']);

Using Entities

use Drago\Database\Entity;

class SampleEntity extends Entity
{
	public const string Table = 'sample';
	public const string PrimaryKey = 'id';

	public ?int $id = null;
	public string $sample;
}

Use the entity in a model, so records are returned as SampleEntity objects:

#[Table(SampleEntity::Table, SampleEntity::PrimaryKey, entity: SampleEntity::class)]
class Model
{
	/** @use Database<SampleEntity> */
	use Database;

	public function __construct(
		protected Connection $connection,
	) {
	}
}

$row = $this->model->get(1)->record();
echo $row->sample;

$rows = $this->model->read('*')->recordAll();

Save Entity Records

Entities are saved the same way as arrays (updated when the primary key is set):

$entity = new SampleEntity;
$entity->id = 1;
$entity->sample = 'sample';

$this->model->save($entity);

Transactions

$this->model->beginTransaction();
try {
	$this->model->save($entity);
	$this->model->commit();
} catch (Throwable $e) {
	$this->model->rollBack();
	throw $e;
}

Entity Generation

For automatic entity generation, consider using the Drago Generator tool: https://github.com/drago-ex/generator