Documentation

CommonModel
in package

Table of Contents

Properties

$db  : mixed
$forge  : mixed

Methods

__construct()  : mixed
addColumnToTable()  : bool
Adds a new column to the specified table.
count()  : int
Counts the number of records in the specified table that match the given conditions.
create()  : int
Inserts a new record into the specified table and returns the insert ID.
createMany()  : mixed
Inserts multiple records into the specified table.
drpForeignKey()  : bool
Drop a foreign key to the specified table.
drpKey()  : bool
Drop a key to the specified table.
drpPrimaryKey()  : bool
Drop a primary key to the specified table.
edit()  : bool
Updates records in the specified table based on the given conditions.
emptyTableDatas()  : bool
Truncates the specified table, removing all records while keeping the table structure intact.
getTableFields()  : array<string|int, mixed>
Retrieves the fields of the specified table.
getTableList()  : array<string|int, mixed>
Retrieves the list of tables in the database.
isHave()  : int
Checks if there are any records in the specified table that match the given conditions.
lists()  : array<string|int, mixed>|null|false
modifyColumnInfos()  : bool
Modifies the column information of the specified table.
newDatabase()  : bool
Creates a new database with the specified name.
newTable()  : bool
Creates a new table in the database with the specified fields and options.
notWhereInList()  : object
Retrieves records from the specified table, excluding those where the given key matches any value in the specified array, with optional joins and sorting.
remove()  : bool
Deletes records from the specified table based on the given conditions.
removeColumnFromTable()  : bool
Removes the specified columns from the table.
removeDatabase()  : bool
Removes the specified database.
removeTable()  : bool
Removes the specified table from the database.
research()  : object
Retrieves records from the specified table that match the given conditions and like patterns.
selectOne()  : object|null
Selects a single record from the database based on conditions.
updateTableName()  : bool
Updates the name of the specified table.
whereInCheckData()  : int
Checks if there are records in the table where a specified column's value matches any of the provided values.

Properties

Methods

__construct()

public __construct([string $group = 'default' ]) : mixed
Parameters
$group : string = 'default'

addColumnToTable()

Adds a new column to the specified table.

public addColumnToTable(string $table, array<string|int, mixed> $fields) : bool
Parameters
$table : string

The name of the table to modify.

$fields : array<string|int, mixed>

An associative array of fields and their data types.

Tags
throws
InvalidArgumentException

If the parameters are invalid.

since
1.2.0
example

// Example usage: $table = 'users'; $fields = [ 'preferences' => ['type' => 'TEXT', 'after' => 'another_field'], ]; if($this->commonModel->addColumnToTable($table, $fields)) { echo 'Column added successfully.'; } else { echo 'Failed to add the column.'; }

// This will add a new column named 'preferences' of type TEXT to the 'users' table, after the 'another_field' column.

Return values
bool

Returns true on success, false on failure.

count()

Counts the number of records in the specified table that match the given conditions.

public count(string $table[, array<string|int, mixed> $where = [] ]) : int
Parameters
$table : string
$where : array<string|int, mixed> = []
Tags
example

// Example parameters: $table = 'orders'; $where = ['status' => 'completed'];

// You can use this function like this: $count = $this->commonModel->count($table, $where);

// To display the count of matching records: echo "Number of matching records: " . $count;

// If no conditions are specified, the count will include all records in the table: $countAll = $this->commonModel->count($table); echo "Total number of records: " . $countAll;

throws
InvalidArgumentException
since
1.0.0
Return values
int

Returns the count of rows that match the condition

create()

Inserts a new record into the specified table and returns the insert ID.

public create(string $table[, array<string|int, mixed> $data = [] ]) : int

This method allows you to insert a new record into a database table. After the record is inserted, it returns the ID of the inserted row.

Parameters
$table : string
$data : array<string|int, mixed> = []
Tags
example

// Example usage: $table = 'users'; $data = [ 'name' => 'John Doe', 'email' => 'john@example.com', 'status' => 1 ];

// Insert a new user record and get the insert ID: $insertId = $this->commonModel->create($table, $data);

if ($insertId) { echo "New user created with ID: " . $insertId; } else { echo "Failed to create user."; }

throws
InvalidArgumentException
since
1.0.0
Return values
int

Returns the ID of the newly inserted record. If the table doesn't have an auto-incremented primary key, it may return 0.

createMany()

Inserts multiple records into the specified table.

public createMany(string $table, array<string|int, mixed> $data) : mixed

This method inserts an array of data into the table in a batch operation. It is useful for bulk inserts where multiple rows need to be added simultaneously.

Parameters
$table : string

The name of the table where the records will be inserted.

$data : array<string|int, mixed>

A multi-dimensional array where each sub-array represents a row of data to insert. Each sub-array's keys should match the column names. Example: [['name' => 'John', 'email' => 'john@example.com'], ['name' => 'Jane', 'email' => 'jane@example.com']].

Tags
example

// Example usage: $table = 'users'; $data = [ ['name' => 'John Doe', 'email' => 'john@example.com', 'status' => 1], ['name' => 'Jane Doe', 'email' => 'jane@example.com', 'status' => 1] ];

// Insert multiple records into the users table: $result = $this->commonModel->createMany($table, $data);

if ($result) { echo "Records inserted successfully."; } else { echo "Failed to insert records."; }

throws
InvalidArgumentException

If the $data array is empty or invalid.

since
1.1.0
Return values
mixed

Returns true on success, false on failure, or the number of rows inserted (based on the database driver used).

drpForeignKey()

Drop a foreign key to the specified table.

public drpForeignKey(string $tableName, string $foreignKeyName) : bool
Parameters
$tableName : string

The name of the table to modify.

$foreignKeyName : string

The name of the foreign key to drop.

Tags
throws
InvalidArgumentException

If the parameters are invalid.

since
1.2.0
example

// Example usage: $tableName = 'orders'; $foreignKeyName = 'fk_orders_users'; // The name of the foreign key to drop if ($this->commonModel->drpForeignKey($tableName, $foreignKeyName)) { echo 'Foreign key dropped successfully.'; } else { echo 'Failed to drop the foreign key.'; }

// This will remove the specified foreign key from the 'orders' table.

Return values
bool

Returns true on success, false on failure.

drpKey()

Drop a key to the specified table.

public drpKey(string $tableName, string $keyName[, bool $prefixKeyName = true ]) : bool
Parameters
$tableName : string

The name of the table to modify.

$keyName : string

The name of the key to drop.

$prefixKeyName : bool = true

Whether to prefix the key name with the table name.

Tags
throws
InvalidArgumentException

If the parameters are invalid.

since
1.2.0
example

// Example usage: $tableName = 'users'; $keyName = 'my_key_name'; $prefixKeyName = true; // Set to true to prefix the key name with the table name if ($this->commonModel->drpKey($tableName, $keyName, $prefixKeyName)) { echo 'Key dropped successfully.'; } else { echo 'Failed to drop the key.'; }

// This will remove the specified key from the 'users' table.

Return values
bool

Returns true on success, false on failure.

drpPrimaryKey()

Drop a primary key to the specified table.

public drpPrimaryKey(string $tableName) : bool
Parameters
$tableName : string

The name of the table to modify.

Tags
throws
InvalidArgumentException

If the parameters are invalid.

since
1.2.0
example

// Example usage: $tableName = 'users'; if ($this->commonModel->drpPrimaryKey($tableName)) { echo 'Primary key dropped successfully.'; } else { echo 'Failed to drop the primary key.'; }

// This will remove the primary key from the 'users' table.

Return values
bool

Returns true on success, false on failure.

edit()

Updates records in the specified table based on the given conditions.

public edit(string $table[, array<string|int, mixed> $data = [] ][, array<string|int, mixed> $where = [] ]) : bool

This method updates one or more rows in the table where the specified conditions match. The $data array contains the new values for the columns, and the $where array specifies the conditions to find the records to update.

Parameters
$table : string

The name of the table where the records will be updated.

$data : array<string|int, mixed> = []

An associative array of column-value pairs that represent the new values. Example: ['name' => 'John', 'email' => 'john@example.com'].

$where : array<string|int, mixed> = []

An associative array of conditions used to filter the records to be updated. Example: ['id' => 1].

Tags
example

// Example usage: $table = 'users'; $data = ['name' => 'John Doe', 'email' => 'john@example.com']; $where = ['id' => 1];

// Update the user record with ID 1: $result = $this->commonModel->edit($table, $data, $where);

if ($result) { echo "Record updated successfully."; } else { echo "Failed to update record."; }

throws
InvalidArgumentException
since
1.0.0
Return values
bool

Returns true if the update was successful, false otherwise.

emptyTableDatas()

Truncates the specified table, removing all records while keeping the table structure intact.

public emptyTableDatas(string $table) : bool
Parameters
$table : string

The name of the table to truncate.

Tags
version
1.2.0

Changed the method name from truncateTable to emptyTableDatas.

throws
InvalidArgumentException

If the table name is invalid or not provided.

since
1.1.9
example

// Example usage: $table = 'users';

if ($this->commonModel->emptyTableDatas($table)) { echo 'Table truncated successfully.'; } else { echo 'Failed to truncate the table.'; }

// This will remove all rows from the 'users' table without deleting the table itself.

Return values
bool

Returns true on success, false on failure.

getTableFields()

Retrieves the fields of the specified table.

public getTableFields(string $tableName) : array<string|int, mixed>
Parameters
$tableName : string

The name of the table to retrieve fields from.

Tags
throws
InvalidArgumentException

If the table name is invalid or not provided.

since
1.2.0
example

// Example usage: $tableName = 'users';

$fields = $this->commonModel->getTableFields($tableName);

foreach ($fields as $field) { echo $field->name . ' - ' . $field->type . '
'; }

// This will print the names and types of all fields in the 'users' table.

Return values
array<string|int, mixed>

Returns an array of field objects.

getTableList()

Retrieves the list of tables in the database.

public getTableList() : array<string|int, mixed>
Tags
since
1.2.0
example

// Example usage: $tables = $this->commonModel->getTableList();

foreach ($tables as $table) { echo $table . '
'; }

// This will print the names of all tables in the database.

Return values
array<string|int, mixed>

Returns an array of table names.

isHave()

Checks if there are any records in the specified table that match the given conditions.

public isHave(string $table, array<string|int, mixed> $where) : int
Parameters
$table : string
$where : array<string|int, mixed>
Tags
example

// Example parameters: $table = 'products'; $where = ['category_id' => 10, 'status' => 'active'];

// You can use this function like this: $count = $this->commonModel->isHave($table, $where);

// To display the count of matching records: echo "Number of matching records: " . $count;

throws
InvalidArgumentException
since
1.0.0
Return values
int

Returns the number of rows that match the condition.

lists()

public lists(string $table[, string $select = '*' ][, array<string|int, mixed> $where = [] ][, string $order = 'id ASC' ][, int $limit = 0 ][, int $pkCount = 0 ][, array<string|int, mixed> $like = [] ][, array<string|int, mixed> $orWhere = [] ][, array<string|int, mixed> $joins = [] ][, array<string|int, mixed> $options = ['isReset' => false] ]) : array<string|int, mixed>|null|false
Parameters
$table : string

// table name

$select : string = '*'

// Coluns to select

$where : array<string|int, mixed> = []

// Where conditions

$order : string = 'id ASC'

// Sorting criteria

$limit : int = 0

// Limit on the number of results

$pkCount : int = 0

// Primary key count

$like : array<string|int, mixed> = []

// Like conditions

$orWhere : array<string|int, mixed> = []

// Or conditions

$joins : array<string|int, mixed> = []

// Join operations

$options : array<string|int, mixed> = ['isReset' => false]
Tags
example

// Example parameters: $table= 'users'; $select = 'id, name, email, ...'; $where = ['status' => 1, ...]; $order = 'created_at DESC'; $limit = 10; $pkCount = 1; $like = ['name' => 'John', ...]; $orWhere = ['role' => 'admin', ...]; $joins = [['table' => 'roles', 'cond' => 'users.role_id = roles.id', 'type' => 'left'], ...];

// You can use this function in a Controller or Library like this: $result=$this->commonModel->lists($table, $select, $where, $order, $limit, $pkCount, $like, $orWhere, $joins); // Once the results are returned, you can process the data using a foreach loop: foreach ($result as $row) { echo $row->name . ' - ' . $row->email; }

// If no results are returned, make sure to handle null checks: if (!$result) { echo "No records found."; }

throws
InvalidArgumentException
since
1.0.0
version
1.1.1

Added LIMIT functionality.

version
1.1.4

Added LIKE functionality.

version
1.1.8

Added OR WHERE functionality.

version
1.1.9

Added $options and JOIN functionality.

Return values
array<string|int, mixed>|null|false

Returns the result object on success, null if no results, or false on failure.

modifyColumnInfos()

Modifies the column information of the specified table.

public modifyColumnInfos(string $table, array<string|int, mixed> $fields) : bool
Parameters
$table : string

The name of the table to modify.

$fields : array<string|int, mixed>

An associative array of fields and their new data types.

Tags
throws
InvalidArgumentException

If the parameters are invalid.

since
1.2.0
example

// Example usage: $table = 'users'; $fields = [ 'old_name' => [ 'name' => 'new_name', 'type' => 'TEXT', 'null' => false, ], ]; $isModified = $this->commonModel->modifyColumnInfos($table, $fields);

// This will change the 'old_name' column to 'new_name' with type TEXT and not null in the 'users' table.

Return values
bool

Returns true on success, false on failure.

newDatabase()

Creates a new database with the specified name.

public newDatabase(string $dbName) : bool
Parameters
$dbName : string
Tags
throws
InvalidArgumentException

If the database name is invalid or not provided.

since
1.2.0
example

// Example usage: $dbName = 'new_database'; if ($this->commonModel->newDatabase($dbName)) { echo 'Database created successfully.'; } else { echo 'Failed to create the database.'; }

// This will create a new database named 'new_database' on the server.

Return values
bool

newTable()

Creates a new table in the database with the specified fields and options.

public newTable(string $table, array<string|int, mixed> $fields[, array<string|int, mixed> $addKeys = ['keys' => [], 'primary' => false, 'unique' => false, 'keyName' => ''] ][, array<string|int, mixed> $foreignKeyFilled = ['field' => '', 'referenceTable' => '', 'referenceField' => '', 'onDelete' => '', 'onUpdate' => '', 'fkName' => ''] ]) : bool
Parameters
$table : string

The name of the table to create.

$fields : array<string|int, mixed>

An associative array of fields and their data types.

$addKeys : array<string|int, mixed> = ['keys' => [], 'primary' => false, 'unique' => false, 'keyName' => '']

Optional keys to add to the table.

$foreignKeyFilled : array<string|int, mixed> = ['field' => '', 'referenceTable' => '', 'referenceField' => '', 'onDelete' => '', 'onUpdate' => '', 'fkName' => '']

Optional foreign key constraints.

Tags
throws
InvalidArgumentException

If the parameters are invalid.

since
1.2.0
example

//Example usage: $table = 'new_table'; $fields = [ 'id' => [ 'type' => 'INT', 'constraint' => 5, 'unsigned' => true, 'auto_increment' => true, ], 'title' => [ 'type' => 'VARCHAR', 'constraint' => '100', 'unique' => true, ], 'author' => [ 'type' => 'VARCHAR', 'constraint' => 100, 'default' => 'King of Town', ], 'description' => [ 'type' => 'TEXT', 'null' => true, ], 'status' => [ 'type' => 'ENUM', 'constraint' => ['publish', 'pending', 'draft'], 'default' => 'pending', ], ];

$addKeys = [ 'keys'=>['blog_name', 'blog_label'], 'primary'=>false, 'unique'=>false, 'keyName'=>'my_key_name' ] if($this->commonModel->newTable($table, $fields, $addKeys)) { echo 'Table added successfully.'; } else { echo 'Failed to add the table.'; }

// This will create a new table named 'new_table' with the specified fields and options.

Return values
bool

Returns true on success, false on failure.

notWhereInList()

Retrieves records from the specified table, excluding those where the given key matches any value in the specified array, with optional joins and sorting.

public notWhereInList(string $table[, string $select = '*' ][, array<string|int, mixed> $joins = [] ][, string $whereInKey = '' ][, array<string|int, mixed> $whereInData = [] ][, string $orderBy = 'queue ASC' ]) : object
Parameters
$table : string

The name of the table to query.

$select : string = '*'

Columns to select, separated by commas. Defaults to '*' to select all columns.

$joins : array<string|int, mixed> = []

Array of join conditions, where each element is an associative array with keys 'table', 'cond', and 'type' for the join table, condition, and type respectively.

$whereInKey : string = ''

The column to check for exclusion based on the values in $whereInData.

$whereInData : array<string|int, mixed> = []

An array of values that should be excluded from the results.

$orderBy : string = 'queue ASC'

Column and direction by which to order the results, defaults to 'queue ASC'.

Tags
throws
InvalidArgumentException

If the parameters are invalid.

since
1.1.8
example

// Example parameters: $table = 'orders'; $select = 'id, customer_name, order_date'; $joins = [ ['table' => 'customers', 'cond' => 'orders.customer_id = customers.id', 'type' => 'inner'] ]; $whereInKey = 'order_status'; $whereInData = ['canceled', 'returned']; $orderBy = 'order_date DESC';

// Usage example: $results = $this->commonModel->notWhereInList($table, $select, $joins, $whereInKey, $whereInData, $orderBy);

// Processing the results: foreach ($results as $row) { echo $row->id . ' - ' . $row->customer_name . ' - ' . $row->order_date . '
'; }

// This will retrieve orders that are not 'canceled' or 'returned', sorted by order date in descending order. // If no records match the criteria, an empty result object is returned.

Return values
object

Returns an object containing the result set.

remove()

Deletes records from the specified table based on the given conditions.

public remove(string $table[, array<string|int, mixed> $where = [] ]) : bool

This method deletes one or more rows in the table where the specified conditions match. The $where array is used to specify the conditions for finding the records to be deleted.

Parameters
$table : string

The name of the table from which the records will be deleted.

$where : array<string|int, mixed> = []

An associative array of conditions used to filter the records to be deleted. Example: ['id' => 1].

Tags
example

// Example usage: $table = 'users'; $where = ['id' => 1];

// Delete the user record with ID 1: $result = $this->commonModel->remove($table, $where);

if ($result) { echo "Record deleted successfully."; } else { echo "Failed to delete record."; }

throws
InvalidArgumentException

If the $where array is empty or invalid.

since
1.0.0
Return values
bool

Returns true if the delete operation was successful, false otherwise.

removeColumnFromTable()

Removes the specified columns from the table.

public removeColumnFromTable(string $table, array<string|int, mixed> $fields) : bool
Parameters
$table : string

The name of the table to modify.

$fields : array<string|int, mixed>

An array of column names to remove.

Tags
throws
InvalidArgumentException

If the parameters are invalid.

since
1.2.0
example

// Example usage: $table = 'users'; $fields = ['preferences', 'another_field']; $isDropped = $this->commonModel->removeColumnFromTable($table, $fields);

// This will remove the 'preferences' and 'another_field' columns from the 'users' table.

Return values
bool

Returns true on success, false on failure.

removeDatabase()

Removes the specified database.

public removeDatabase(string $dbName) : bool
Parameters
$dbName : string

The name of the database to remove.

Tags
throws
InvalidArgumentException

If the database name is invalid or not provided.

since
1.2.0
example

// Example usage: $dbName = 'old_database';

if ($this->commonModel->removeDatabase($dbName)) { echo 'Database removed successfully.'; } else { echo 'Failed to remove the database.'; }

// This will delete the 'old_database' from the server.

Return values
bool

Returns true on success, false on failure.

removeTable()

Removes the specified table from the database.

public removeTable(string $table) : bool
Parameters
$table : string

The name of the table to remove.

Tags
throws
InvalidArgumentException

If the table name is invalid or not provided.

since
1.2.0
example

// Example usage: $table = 'old_table';

if ($this->commonModel->removeTable($table)) { echo 'Table removed successfully.'; } else { echo 'Failed to remove the table.'; }

// This will delete the 'old_table' from the database.

Return values
bool

Returns true on success, false on failure.

research()

Retrieves records from the specified table that match the given conditions and like patterns.

public research(string $table[, array<string|int, mixed> $like = [] ][, string $select = '*' ][, array<string|int, mixed> $where = [] ]) : object
Parameters
$table : string

The name of the table to query.

$like : array<string|int, mixed> = []

Associative array of LIKE conditions, where the keys are column names and the values are the search patterns.

$select : string = '*'

Columns to select, separated by commas. Defaults to '*' to select all columns.

$where : array<string|int, mixed> = []

Associative array of WHERE conditions.

Tags
throws
InvalidArgumentException

If the parameters are invalid.

since
1.0.0
example

// Example parameters: $table = 'products'; $like = ['name' => 'Gadget']; // Search for 'Gadget' in the 'name' column $select = 'id, name, price'; // Select specific columns $where = ['status' => 'available']; // Filter by 'status'

// Usage example: $results = $this->commonModel->research($table, $like, $select, $where);

// Processing the results: foreach ($results as $row) { echo $row->id . ' - ' . $row->name . ' - $' . $row->price . '
'; }

// If no records match the criteria, an empty result object is returned.

Return values
object

Returns an object containing the result set.

selectOne()

Selects a single record from the database based on conditions.

public selectOne(string $table[, array<string|int, mixed> $where = [] ][, string $select = '*' ][, string $order = 'id ASC' ]) : object|null
Parameters
$table : string
$where : array<string|int, mixed> = []
$select : string = '*'
$order : string = 'id ASC'
Tags
version
1.1.2

Added ORDER functionality.

example

// Example parameters: $table = 'users'; $where = ['id' => 1]; $select = 'id, name, email'; $order = 'created_at DESC';

// You can use this function like this: $result = $this->commonModel->selectOne($table, $where, $select, $order);

// To display the result: if ($result) { echo $result->name . ' - ' . $result->email; } else { echo "No records found."; }

throws
InvalidArgumentException
since
1.0.0
Return values
object|null

Returns the row object on success or null if no result is found.

updateTableName()

Updates the name of the specified table.

public updateTableName(string $oldName, string $newName) : bool
Parameters
$oldName : string

The current name of the table.

$newName : string

The new name for the table.

Tags
throws
InvalidArgumentException

If the parameters are invalid.

since
1.2.0
example

// Example usage: $oldName = 'old_table_name'; $newName = 'new_table_name'; if($this->commonModel->updateTableName($oldName, $newName)) { echo 'Table name updated successfully.'; } else { echo 'Failed to update the table name.'; }

// This will rename the table from 'old_table_name' to 'new_table_name'.

Return values
bool

Returns true on success, false on failure.

whereInCheckData()

Checks if there are records in the table where a specified column's value matches any of the provided values.

public whereInCheckData(string $att, string $table[, array<string|int, mixed> $where = [] ]) : int
Parameters
$att : string
$table : string
$where : array<string|int, mixed> = []
Tags
example

// Example parameters: $att = 'status'; $table = 'orders'; $where = [1, 2, 3];

// You can use this function like this: $count = $this->commonModel->whereInCheckData($att, $table, $where);

// To display the count of matching records: echo "Number of matching records: " . $count;

throws
InvalidArgumentException
since
1.0.0
Return values
int

Returns the number of rows that match the condition


        
On this page

Search results