Kotchasan Framework Documentation

Kotchasan Framework Documentation

Model Class - Database Access Object

EN 03 Feb 2026 17:09

Model Class - Database Access Object

The Model class serves as the base abstract class for all data models. It simplifies database interactions by acting as a bridge to Kotchasan\Database and various Query Builders.

Namespace

Kotchasan\Model

Usage

Models typically extend this class to encapsulate business logic and database queries.

class ProductModel extends \Kotchasan\Model
{
    // Override connection name if needed
    protected $conn = 'warehouse_db';

    public function findProduct($id)
    {
        return $this->select()->from('products')->where(['id', $id])->first();
    }
}

Properties

$db

Holds the active Kotchasan\Database instance.

  • Visibility: protected

$conn

The configuration key for the database connection.

  • Default: 'default'
  • Visibility: protected (Overrideable)

Static Methods

create()

Factory method to instantiate the model.

public static function create(): static

createQuery()

Create a Query Builder instance directly from the model.

public static function createQuery(): \Kotchasan\QueryBuilder\QueryBuilderInterface

createDb()

Instantiate and return the underlying Database driver.

public static function createDb(): Database

Public Methods

Transaction Management

Control database transactions manually.

public function beginTransaction(): bool
public function commit(): bool
public function rollback(): bool

Query Builder Factories

Methods to initiate fluent query construction.

select()

Start a SELECT query.

public function select(mixed ...$columns): SelectBuilder

Usage:

$q = $model->select('id', 'name');
// OR
$q = $model->select(); // SELECT *

insert()

Start an INSERT query.

public function insert(string $table): InsertBuilder

update()

Start an UPDATE query.

public function update(string $table): UpdateBuilder

delete()

Start a DELETE query.

public function delete(string $table): DeleteBuilder

Database Helpers

raw()

Execute a raw SQL command.

public function raw(string $sql, array $params = []): mixed

lastInsertId()

Get the auto-generated ID of the last INSERT operation.

public function lastInsertId(): int|string

getTableName()

Get the physical table name (including configured prefix).

public function getTableName(string $table): string

getPrefix()

Get the configured table prefix.

public function getPrefix(): string

getDB()

Access the raw Database instance.

public function getDB(): Database

File Size: 216 lines