Skip to main content

Entities

Entities are the core of Jinya Database. They represent a row in a database table and are defined as simple PHP classes that extend Jinya\Database\Entity.

Defining an Entity

To define an entity, create a class and extend Jinya\Database\Entity. Use attributes to map the class and its properties to the database table and columns.

namespace App\Entities;

use Jinya\Database\Entity;
use Jinya\Database\Attributes\Column;
use Jinya\Database\Attributes\Id;
use Jinya\Database\Attributes\Table;

#[Table('artists')]
class Artist extends Entity
{
#[Id]
#[Column(autogenerated: true)]
public int $id;

#[Column(sqlName: 'artist_name')]
public string $name;

#[Column]
public ?string $email = null;
}

Attributes

#[Table]

The #[Table] attribute is used on the class to specify the database table name.

  • name: The name of the table in the database.

If the #[Table] attribute is missing, the short class name will be used as the table name.

#[Column]

The #[Column] attribute is used on public properties to map them to database columns.

  • sqlName: (Optional) The name of the column in the database. Defaults to the property name.
  • autogenerated: (Optional) Boolean indicating if the column is autogenerated (e.g., AUTO_INCREMENT). Defaults to false.
  • unique: (Optional) Boolean indicating if the column has a unique constraint. Defaults to false.
  • defaultValue: (Optional) The default value for the column. Defaults to null.

#[Id]

The #[Id] attribute marks a property as the primary key of the table. Jinya Database currently supports single-column primary keys.

CRUD Operations

Since your entities extend Jinya\Database\Entity, they inherit several methods for common database operations.

Create

To insert a new row into the database, instantiate the entity, set its properties, and call create().

$artist = new Artist();
$artist->name = 'Jinya';
$artist->create();

// The $id property is automatically updated if it's autogenerated
echo $artist->id;

Read (Find)

Entities provide static methods to find rows in the database.

// Find by ID
$artist = Artist::findById(1);

// Find all
$artists = Artist::findAll();
foreach ($artists as $artist) {
echo $artist->name;
}

// Find a range (for pagination)
$artists = Artist::findRange(start: 0, count: 10);

// Count all
$total = Artist::countAll();

Update

To update an existing row, modify the properties of an entity instance and call update().

$artist = Artist::findById(1);
if ($artist) {
$artist->name = 'Updated Name';
$artist->update();
}

Delete

To delete a row, call delete() on an entity instance.

$artist = Artist::findById(1);
if ($artist) {
$artist->delete();
}