drago-ex/database

Connecting to database for Nette Framework

v1.2.0 2024-01-24 05:42 UTC

This package is auto-updated.

Last update: 2024-04-11 11:33:32 UTC


README

Simple recurring questions.

License: MIT PHP version Tests Coding Style CodeFactor Coverage Status

Technology

  • PHP 8.1 or higher
  • composer

Knowledge

Installation

composer require drago-ex/database

Use

#[Table('table', 'id')]
class Model {}

Basic queries in the Repository

Get records from table.

$this->model->table();

Search for a record by column name in the table.

$this->model->table('email = ?', 'email@email.com');

Search for a record by id.

$this->model->get(1);

Delete a record from the database.

$this->model->remove(1);

Save record (the update will be performed if a column with id is added).

$this->model->put(['column' => 'record']);

Use of entity

class SampleEntity extends Drago\Database\Entity
{
	public const Table = 'table';
	public const PrimaryKey = 'id';

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

Basic repository.

#[Table(SampleEntity::Table, SampleEntity::PrimarKey)]
class Repository {}

Use of an entity in a repository.

function find(int $id): array|SampleEntity|null
{
	return $this->get($id)->fetch();
}

Reading data.

$row = $this->find(1);
echo $row->id;
echo $row->sample;

Save records across an entity (to update the record we add id).

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

$this->save($entity);

The save method saves the record to the database.

function save(SampleEntity $entity): Result|int|null
{
	return $this->put($entity);
}

Tips

You can also use entities and have them generated. https://github.com/drago-ex/generator