Query Builder
The DataMapperQuery provides a Laravel-inspired fluent interface for building complex data mapping queries.
Introduction
Section titled “Introduction”The Query Builder combines the power of the DataMapper with an intuitive, chainable API.
Features:
- Laravel-style Fluent Interface - Chainable methods for intuitive query building
- Method Chaining in Any Order - Call methods in whatever order makes sense
- Pipeline Integration - Combine with DataMapper pipelines for data transformation
- WHERE with Comparison Operators -
=,!=,<>,>,<,>=,<= - Advanced WHERE Conditions -
between(),whereIn(),whereNull(),exists(),like() - Nested WHERE Conditions - Use closures for complex AND/OR logic
- OR WHERE Conditions - Combine conditions with OR logic
- ORDER BY, LIMIT, OFFSET - Sort and paginate results
- GROUP BY with Aggregations - COUNT, SUM, AVG, MIN, MAX, FIRST, LAST, COLLECT, CONCAT
- HAVING Clause - Filter grouped results
- DISTINCT - Remove duplicates
Quick Start
Section titled “Quick Start”use event4u\DataHelpers\DataMapper;
$products = [ ['id' => 1, 'name' => 'Laptop', 'category' => 'Electronics', 'price' => 1299], ['id' => 2, 'name' => 'Mouse', 'category' => 'Electronics', 'price' => 29], ['id' => 3, 'name' => 'Desk', 'category' => 'Furniture', 'price' => 299],];
// Simple query$result = DataMapper::query() ->source('products', $products) ->where('category', 'Electronics') ->orderBy('price', 'DESC') ->limit(10) ->get();Basic Usage
Section titled “Basic Usage”Creating a Query
Section titled “Creating a Query”use event4u\DataHelpers\DataMapper;
// Static factory method$query = DataMapper::query();
// Or use constructor$query = new DataMapperQuery();Adding a Data Source
Section titled “Adding a Data Source”$query->source('products', $products);Executing the Query
Section titled “Executing the Query”$result = $query->get();Pipeline Integration
Section titled “Pipeline Integration”Combine the Query Builder with DataMapper pipelines:
use event4u\DataHelpers\DataMapper;use event4u\DataHelpers\DataMapper\Pipeline\Filters\TrimStrings;use event4u\DataHelpers\DataMapper\Pipeline\Filters\LowercaseStrings;
$result = DataMapper::query() ->source('products', $products) ->pipeline([ new TrimStrings(), new LowercaseStrings(), ]) ->where('category', 'Electronics') ->get();WHERE Conditions
Section titled “WHERE Conditions”Basic WHERE
Section titled “Basic WHERE”// Equal$query->where('category', 'Electronics');$query->where('category', '=', 'Electronics');
// Not equal$query->where('status', '!=', 'deleted');$query->where('status', '<>', 'deleted');
// Comparison$query->where('price', '>', 100);$query->where('price', '>=', 100);$query->where('price', '<', 1000);$query->where('price', '<=', 1000);Advanced WHERE
Section titled “Advanced WHERE”// Between$query->between('price', 100, 500);
// In array$query->whereIn('category', ['Electronics', 'Furniture']);
// Not in array$query->whereNotIn('status', ['deleted', 'archived']);
// Null check$query->whereNull('deletedAt');$query->whereNotNull('publishedAt');
// Exists check$query->exists('metadata.tags');
// Like pattern$query->like('name', '%Laptop%');Nested Conditions
Section titled “Nested Conditions”$query->where(function($q) { $q->where('category', 'Electronics') ->where('price', '>', 100);})->orWhere(function($q) { $q->where('category', 'Furniture') ->where('price', '<', 500);});OR Conditions
Section titled “OR Conditions”$query->where('category', 'Electronics') ->orWhere('category', 'Furniture');Sorting
Section titled “Sorting”ORDER BY
Section titled “ORDER BY”// Ascending$query->orderBy('price');$query->orderBy('price', 'ASC');
// Descending$query->orderBy('price', 'DESC');
// Multiple columns$query->orderBy('category', 'ASC') ->orderBy('price', 'DESC');Limiting Results
Section titled “Limiting Results”LIMIT and OFFSET
Section titled “LIMIT and OFFSET”// Limit$query->limit(10);
// Offset$query->offset(20);
// Pagination$query->limit(10)->offset(20); // Page 3Grouping and Aggregations
Section titled “Grouping and Aggregations”GROUP BY
Section titled “GROUP BY”$query->groupBy('category');
// Multiple fields$query->groupBy(['category', 'brand']);Aggregations
Section titled “Aggregations”$query->groupBy('category') ->aggregations([ 'total' => ['COUNT'], 'avgPrice' => ['AVG', '{{ products.*.price }}'], 'maxPrice' => ['MAX', '{{ products.*.price }}'], ]);HAVING Clause
Section titled “HAVING Clause”$query->groupBy('category') ->aggregations([ 'total' => ['COUNT'], ]) ->having('total', '>', 5);Other Operators
Section titled “Other Operators”DISTINCT
Section titled “DISTINCT”$query->distinct();SELECT Fields
Section titled “SELECT Fields”$query->select(['name', 'price']);Complete Examples
Section titled “Complete Examples”Filter and Sort Products
Section titled “Filter and Sort Products”$result = DataMapper::query() ->source('products', $products) ->where('category', 'Electronics') ->where('price', '>', 100) ->orderBy('price', 'DESC') ->limit(10) ->get();Group and Aggregate
Section titled “Group and Aggregate”$result = DataMapper::query() ->source('orders', $orders) ->groupBy('customerId') ->aggregations([ 'totalOrders' => ['COUNT'], 'totalSpent' => ['SUM', '{{ orders.*.amount }}'], 'avgOrder' => ['AVG', '{{ orders.*.amount }}'], ]) ->having('totalOrders', '>', 5) ->get();Complex Filtering
Section titled “Complex Filtering”$result = DataMapper::query() ->source('users', $users) ->where(function($q) { $q->where('role', 'admin') ->orWhere('role', 'moderator'); }) ->where('active', true) ->whereNotNull('emailVerifiedAt') ->orderBy('createdAt', 'DESC') ->limit(50) ->get();With Pipeline
Section titled “With Pipeline”use event4u\DataHelpers\DataMapper\Pipeline\Filters\TrimStrings;use event4u\DataHelpers\DataMapper\Pipeline\Filters\RemoveEmpty;
$result = DataMapper::query() ->source('products', $products) ->pipeline([ new TrimStrings(), new RemoveEmpty(), ]) ->where('category', 'Electronics') ->where('price', '>', 100) ->orderBy('price', 'ASC') ->get();Method Reference
Section titled “Method Reference”Query Building
Section titled “Query Building”source(string $name, mixed $data)- Add data sourcewhere(string|Closure $field, mixed $operator = null, mixed $value = null)- Add WHERE conditionorWhere(string|Closure $field, mixed $operator = null, mixed $value = null)- Add OR WHERE conditionbetween(string $field, mixed $min, mixed $max)- Add BETWEEN conditionwhereIn(string $field, array $values)- Add IN conditionwhereNotIn(string $field, array $values)- Add NOT IN conditionwhereNull(string $field)- Add NULL checkwhereNotNull(string $field)- Add NOT NULL checkexists(string $field)- Add EXISTS checklike(string $field, string $pattern)- Add LIKE condition
Sorting and Limiting
Section titled “Sorting and Limiting”orderBy(string $field, string $direction = 'ASC')- Add ORDER BYlimit(int $limit)- Set LIMIToffset(int $offset)- Set OFFSET
Grouping
Section titled “Grouping”groupBy(string|array $fields)- Add GROUP BYaggregations(array $aggregations)- Add aggregationshaving(string $field, string $operator, mixed $value)- Add HAVING condition
distinct()- Remove duplicatesselect(array $fields)- Select specific fieldspipeline(array $filters)- Add pipeline filtersget()- Execute query and get results
See Also
Section titled “See Also”- DataMapper - DataMapper guide
- Template Expressions - Template syntax
- Pipelines - Pipeline processing