The arrayToSql function in KConverter provides a flexible way to construct SQL queries from an array-based input. This function is designed to handle complex queries, including table joins, conditions, sorting, and aggregation. It can be used to generate SQL queries dynamically for execution in the Ketroute Framework.
public static function arrayToSql(array $core_data_source, array ...$join_data_source): string
Core Data Source ($core_data_source)
The first parameter represents the main table and the query structure:
Simple field names: ['field1', 'field2']
Aggregated fields: ['field3' => 'SUM']
Aliased fields with functions: ['field4' => ['field_alias', 'UPPER']]
Direct equality: ['field' => 1]
OR conditions: ['OR' => ['field' => 520, 'field' => [2,5,9], 'field' => null]]
IGNORE (fields that should not match): ['IGNORE' => ['field' => 520]]
Join Data Source ($join_data_source)
Simple join: [ ['jointable1_id', 'parent_table_id'] ]
Complex join: [ ['jointable1_id', 'parent_table_id', 'optional_joinindex'] ]
Simple Query
$query = KConverter::arrayToSql([
'users',
['id', 'name', ['created_at' => 'DATE']],
['status' => 'active'],
'mysql',
10,
[['created_at', 'DESC']]
]);
SELECT id, name, DATE(created_at) FROM users WHERE status = 'active' ORDER BY created_at DESC LIMIT 10;
$query = KConverter::arrayToSql([
'orders',
['id', 'total', ['created_at' => 'DATE']],
['status' => 'pending']
], [
'customers',
[['customer_id', 'orders.customer_id']],
[],
['name', 'email'],
'LEFT'
]);
SELECT orders.id, orders.total, DATE(orders.created_at), customers.name, customers.email
FROM orders
LEFT JOIN customers ON customers.customer_id = orders.customer_id
WHERE orders.status = 'pending';
Once the SQL query is generated, it can be executed using KetrouteApplication::db()->runSql($query)
$result = KetrouteApplication::db()->runSql($query);
This function is a powerful utility for generating queries dynamically without manually writing SQL statements.
Your download is here.