Query builder components
Sparkle's Query Builder provides an elegant and fluent interface for constructing SQL queries in PHP. This documentation covers the available methods, their full method signatures, and examples.
Initialization
To start building a query, use the Sparkle::table() method:
$builder = Sparkle::table('users');Methods
Limit
Set the LIMIT clause for the query.
limit(int $limit): BuilderArguments:
$limit(int): The number of records to retrieve. This defines the maximum number of results returned by the query.
Return:
Builder: Returns the current instance of the query builder, allowing for method chaining.
Example Usage:
// Set limit to maximum 10 rows.
$query = Sparkle::table('users')->limit(10);Offset
Set the OFFSET clause for the query.
offset(int $offset): BuilderArguments:
$offset(int): The number of records to skip before starting to return results. Typically used in pagination, where you might skip a set of records and start from a specific point.
Return:
Builder: Returns the current instance of the query builder, allowing for method chaining.
Example Usage:
// Skips the first 5 records and retrieves the next 10
$query = Sparkle::table('users')->offset(5)->limit(10);OrderBy
Adds an ORDER BY clause to the query to specify the sorting order of the results.
orderBy(string $column, string $direction = 'asc'): BuilderArguments:
$column(string): The name of the column to sort the results by.$direction(string, optional): The sorting direction. You can set it to:'asc': Sort in ascending order (default).'desc': Sort in descending order.
Return:
Builder: Returns the current instance of the query builder, allowing method chaining.
Example Usage:
// Orders the results by the 'name' column in ascending order (default)
$query = Sparkle::table('users')->orderBy('name');
// Orders the results by the 'age' column in descending order
$query = Sparkle::table('users')->orderBy('age', 'desc');GroupBy
Adds a GROUP BY clause to the query, which groups the results based on a specific column.
groupBy(string $column): BuilderArguments:
$column(string): The name of the column to group the results by.
Return:
Builder: Returns the current instance of the query builder, allowing method chaining.
Example Usage:
// Groups the results by the 'category' column
$query = Sparkle::table('products')->groupBy('category');Having
Adds a HAVING clause to the query. The HAVING clause is used to filter records after they have been grouped (typically used with GROUP BY).
having(string $column, string $operator, string $value): BuilderArguments:
$column(string): The name of the column to apply the condition on.$operator(string): The comparison operator (e.g.,'=','>','<', etc.).$value(string): The value to compare the column against.
Return:
Builder: Returns the current instance of the query builder, allowing method chaining.
Example Usage:
// Retrieves products grouped by 'category' and filters those with a total sales greater than 100
$query = Sparkle::table('products')
->groupBy('category')
->having('total_sales', '>', '100');Where
Adds a WHERE clause to the query.
where(string $column, ComparisonOperator $comparisonOperator, string $value): BuilderArguments:
- $column (
string): The name of the column to apply the condition on. - $comparisonOperator (
Sirmerdas\Sparkle\Enums\ComparisonOperator\ComparisonOperator): The comparison operator to use for the condition (e.g.,ComparisonOperator::EQUAL,ComparisonOperator::GREATER_THAN,ComparisonOperator::LESS_THAN). - $value (
string): The value to compare the column against.
TIP
For ComparisonOperator, check out ComparisonOperator Enum
Return:
Returns the current instance of the query builder for method chaining.
Example:
Sparkle::table('users')->where('age', ComparisonOperator::GREATER_THAN, '18');OrWhere
Adds an OR WHERE clause to the query.
orWhere(string $column, ComparisonOperator $comparisonOperator, string $value): BuilderArguments:
- $column (
string): The name of the column to apply the condition on. - $comparisonOperator (
ComparisonOperator): The comparison operator to use (e.g.,ComparisonOperator::EQUAL,ComparisonOperator::NOT_EQUAL). - $value (
string): The value to compare the column against.
Return:
Returns the current instance of the query builder for method chaining.
Example:
Sparkle::table('users')->where('age', ComparisonOperator::GREATER_THAN, '18')->orWhere('status', ComparisonOperator::EQUAL, 'active');WhereNull
Adds a condition to check if a column is NULL.
whereNull(string $column): BuilderArguments:
- $column (
string): The name of the column to check forNULL.
Return:
Returns the current instance of the query builder for method chaining.
Example:
Sparkle::table('users')->whereNull('deleted_at');WhereIn
Adds a WHERE IN clause to the query.
whereIn(string $column, array $values): BuilderArguments:
- $column (
string): The name of the column to apply theWHERE INcondition on. - $values (
array): An array of values to match against the column.
Return:
Returns the current instance of the query builder for method chaining.
Example:
Sparkle::table('users')->whereIn('id', [1, 2, 3]);OrWhereIn
Adds an OR WHERE IN clause to the query.
orWhereIn(string $column, array $values): BuilderArguments:
- $column (
string): The name of the column to apply theWHERE INcondition on. - $values (
array): An array of values to match against the column.
Return:
Returns the current instance of the query builder for method chaining.
Example:
Sparkle::table('users')->orWhereIn('category_id', [1, 2, 3]);WhereNotIn
Adds a WHERE NOT IN clause to the query.
whereNotIn(string $column, array $values): BuilderArguments:
- $column (
string): The name of the column to apply theWHERE NOT INcondition on. - $values (
array): An array of values to exclude from the column.
Return:
Returns the current instance of the query builder for method chaining.
Example:
Sparkle::table('users')->whereNotIn('category_id', [4, 5, 6]);orWhereNotIn
Adds an OR WHERE NOT IN clause to the query.
orWhereNotIn(string $column, array $values): BuilderArguments:
- $column (
string): The name of the column to apply theWHERE NOT INcondition on. - $values (
array): An array of values to exclude from the column.
Return:
Returns the current instance of the query builder for method chaining.
Example:
Sparkle::table('users')->orWhereNotIn('category_id', [4, 5, 6]);WhereNotNull
Adds a condition to check if a column is NOT NULL.
whereNotNull(string $column): BuilderArguments:
- $column (
string): The name of the column to check for NOT NULL.
Return:
Returns the current instance of the query builder for method chaining.
Example:
Sparkle::table('users')->whereNotNull('updated_at');Here’s the README in the requested Laravel style for the provided join method:
Join
Adds a JOIN clause to the query, allowing you to combine rows from two or more tables based on a related column.
join(string $targetTable, string $leftColumn, ComparisonOperator $comparisonOperator, string $rightColumn, JoinType $joinType = JoinType::INNER): BuilderArguments:
- $targetTable (
string): The name of the table to join with. - $leftColumn (
string): The column from the current table to use in the join condition. - $comparisonOperator (
ComparisonOperator): The operator to use for comparison (e.g.,ComparisonOperator::EQUAL,ComparisonOperator::GREATER_THAN,ComparisonOperator::LESS_THAN). - $rightColumn (
string): The column from the target table to use in the join condition. - $joinType (
JoinType): The type of join to perform (e.g.,JoinType::INNER,JoinType::LEFT,JoinType::RIGHT). Defaults toINNER. Check out JoinType
Return:
Returns the current instance of the query builder for method chaining.
Example:
Sparkle::table('orders')
->join('customers', 'orders.customer_id', ComparisonOperator::EQUAL, 'customers.id')
->where('status', ComparisonOperator::EQUAL, 'active');Here’s the README in the requested Laravel style for the provided methods:
Count
Gets the total count of records for the current query.
count(): intReturn:
Returns an int, which is the number of records matching the query.
Example:
$totalRecords = Sparkle::table('users')->count();This will return the total number of records in the users table.
Exists
Determines if any records exist for the current query.
exists(): boolReturn:
Returns a bool:
trueif records exist.falseotherwise.
Example:
$hasRecords = Sparkle::table('users')->exists();This will return true if there are any records in the users table.
Copy
Creates a copy of the current Builder instance.
copy(): BuilderReturn:
Returns a new instance of the Builder class with the same property values.
Example:
$newBuilder = Sparkle::table('users')->copy();This will create a new Builder instance that is a copy of the current instance.
TIP
Use This When you want to use one some chained query result as base query for some rows.
Transaction
Executes a set of database operations within a transaction.
transaction(callable $transactions): voidArguments:
- $transactions (
callable): A callback function that receives a copied instance of the builder and executes database operations within the transaction.
Example:
Sparkle::table('users')->transaction(function (Builder $builder) {
$builder->copy()->createGetId->insert(['name' => 'John Doe']);
$builder->copy()->createGetId->insert(['name' => 'Test Doe']);
$builder->copy()->createGetId->insert(['name' => 'New user']);
});This will execute the insert operation within a database transaction.
Crud operation
Get
Executes the query and retrieves all matching rows.
get(array $columns = ['*']): Sirmerdas\Sparkle\Database\QueryBuilder\QueryResultArguments:
- $columns (
array): The columns to select. Defaults to selecting all columns (['*']).
Return:
Returns an instance of QueryResult containing the result of the query.
INFO
For getting familiar better with QueryResult please visit QueryResult docs.
Example:
$users = Sparkle::table('users')->get();This will return all rows from the users table.
SelectRaw
Executes a raw SQL select query with optional parameters.
selectRaw(string $query, array $params = []): arrayArguments:
- $query (
string): The raw SQL query string to execute. - $params (
array): An optional array of parameters to bind to the query. Defaults to an empty array.
Return:
Returns an array of results, typically as an array of objects.
Example:
$results = Sparkle::table('users')->selectRaw('SELECT * FROM users WHERE age > ?', [30]);This will execute the raw SQL query and return the matching results.
First
Executes the query and retrieves the first matching row.
first(array $columns = ['*']): bool|objectArguments:
- $columns (
array): The columns to select. Defaults to selecting all columns (['*']).
Return:
Returns the first matching row as an object, or false if no rows match.
Example:
$user = Sparkle::table('users')->first();This will return the first row from the users table.
Create
Inserts a new record into the database.
create(array $data): boolArguments:
- $data (
array): An associative array where keys are column names and values are the corresponding data to insert.
Return:
Returns true if at least one row was inserted successfully, otherwise false.
Example:
Sparkle::table('users')->create(['name' => 'John Doe', 'email' => 'john@example.com']);This will insert a new user into the users table.
CreateRaw
Executes a raw SQL insert query with optional parameters.
createRaw(string $query, array $params): intArguments:
- $query (
string): The raw SQL query string to execute. - $params (
array): An array of parameters to bind to the query.
Return:
Returns the ID of the last inserted row.
Example:
$lastInsertId = Sparkle::table('users')->createRaw('INSERT INTO users (name, email) VALUES (?, ?)', ['John Doe', 'john@example.com']);This will execute the raw SQL insert query and return the last inserted ID.
CreateGetId
Inserts a new record into the database and returns the last inserted ID.
createGetId(array $data): intArguments:
- $data (
array): An associative array where keys are column names and values are the corresponding data to insert.
Return:
Returns the ID of the last inserted row.
Example:
$userId = Sparkle::table('users')->createGetId(['name' => 'John Doe', 'email' => 'john@example.com']);This will insert a new user and return the ID of the last inserted user.
Update
Updates records in the database with the provided data.
update(array $data): intArguments:
- $data (
array): An associative array of column-value pairs to update.
Return:
Returns the number of affected rows.
Example:
$updatedRows = Sparkle::table('users')->update(['name' => 'John Doe']);This will update the name field for matching users and return the number of affected rows.
UpdateRaw
Executes a raw SQL update query with optional parameters.
updateRaw(string $query, array $params): intArguments:
- $query (
string): The raw SQL query string to execute. - $params (
array): An array of parameters to bind to the query.
Return:
Returns the number of affected rows.
Example:
$affectedRows = Sparkle::table('users')->updateRaw('UPDATE users SET name = ? WHERE email = ?', ['John Doe', 'john@example.com']);This will execute the raw SQL update query and return the number of affected rows.
Delete
Deletes records from the database based on the provided conditions.
delete(array $delete = []): intArguments:
- $delete (
array): An array of column names to delete from the table. Required when using joins.
Return:
Returns the number of rows affected by the delete operation.
Example:
$deletedRows = Sparkle::table('users')->delete(['name']);This will delete records from the users table based on the provided conditions.
DeleteRaw
Executes a raw SQL delete query with optional parameters.
deleteRaw(string $query, array $params): intArguments:
- $query (
string): The raw SQL query string to execute. - $params (
array): An array of parameters to bind to the query.
Return:
Returns the number of affected rows.
Example:
$deletedRows = Sparkle::table('users')->deleteRaw('DELETE FROM users WHERE name = ?', ['John Doe']);This will execute the raw SQL delete query and return the number of rows affected.
Raw
Executes a raw SQL query with optional parameters and returns the results.
raw(string $query, array $params = []): arrayArguments:
- $query (
string): The SQL query to be executed. - $params (
array): Optional parameters to bind to the query.
Return:
Returns an array with:
'items'(array): The fetched results as objects.'rowCount'(int): The number of affected rows.'lastInsertId'(string|bool): The last inserted ID if applicable.
Example:
$result = Sparkle::table('users')->raw('SELECT * FROM users WHERE age > ?', [30]);This will execute the raw SQL query and return the results, including the number of affected rows and the last inserted ID.
Example
This is an example of method chaining using Sparkle package
Sparkle::table('orders')
->where('status', ComparisonOperator::EQUAL, 'shipped')
->join('customers', 'orders.customerNumber', ComparisonOperator::EQUAL, 'customers.customerNumber')
->join('orderdetails','orders.orderNumber',ComparisonOperator::EQUAL,'orderdetails.orderNumber')
->join('products','orderdetails.productCode',ComparisonOperator::EQUAL,'products.productCode')
->orderBy('orderDate', 'desc')
->where('produscts.productName',ComparisonOperator::LIKE,'%FORD%')
->limit(100)
->get();