ZTeraDB Query Builder Guide
The ZTeraDBQuery class helps you build database queries without writing SQL.
π― What is ZTeraDBQuery?
It is a chainable query builder that lets you perform:
- SELECT
- INSERT
- UPDATE
- DELETE
- Filtering
- Sorting
- Pagination
- Related field lookups (joins)
Example:
$query = (new ZTeraDBQuery("user"))->select();
π§ How Query Building Works
Start Query
β
Choose Type (select/insert/update/delete)
β
Add Fields (optional)
β
Apply Filters
β
Run the Query
π Creating a Query
$query = new ZTeraDBQuery("schemaName");
schemaName β table/schema in your ZTeraDB instance
Example: "user", "product", "order"
π₯ Query Types
1οΈβ£ SELECTβ
$query = (new ZTeraDBQuery("user"))->select();
2οΈβ£ INSERTβ
$query = (new ZTeraDBQuery("user"))
->insert()
->fields([
"email" => "test@site.com",
"status" => true
]);
3οΈβ£ UPDATEβ
$query = (new ZTeraDBQuery("user"))
->update()
->fields(["status" => false])
->filter(["id" => 1]);
4οΈβ£ DELETEβ
$query = (new ZTeraDBQuery("user"))
->delete()
->filter(["id" => 5]);
π· fields() β Selecting, Inserting, Updating
SELECT Specific Fieldsβ
$query->select()->fields([
"email" => 1,
"status" => 1
]);
INSERT New Rowβ
$query->insert()->fields([
"name" => "John",
"email" => "john@test.com",
"status" => true
]);
UPDATE Existing Rowβ
$query->update()->fields([
"status" => false
]);
π― Basic Filters (filter)
Use .filter(["field" => value]) for simple equality checks:
$query->filter(["status" => true]);
$query->filter(["id" => 10]);
$query->filter(["email" => "abc@test.com"]);
Equivalent to:
WHERE status = true
π Advanced Filters (filterCondition)
Advanced filters allow:
- Math operations
- AND / OR conditions
- String filters
- Comparisons
(>, <, >=, <=)
Example:
$query->filterCondition(
ZTEQUAL(
ZTMUL(["price", "quantity"]),
200
)
);
Equivalent SQL:
WHERE price * quantity = 200
π relatedFields() β Joins Made Easy
Fetch data from related schemas.
Example:
$userFilter = (new ZTeraDBQuery("user"))
->select()
->fields(["email" => 1])
->filter(["status" => true]);
$query = (new ZTeraDBQuery("order"))
->select()
->relatedFields([
"user" => $userFilter
]);
π Sorting
$query->sort(["price" => 1]); // ascending
$query->sort(["price" => -1]); // descending
Equivalent:
- 1 β ASC
- -1 β DESC
π limit(start, end) β Pagination
$query->limit(0, 10); // first 10 rows
π’ count()
Returns number of matching records instead of row data.
$query->count();
π§ͺ Full Example
$query = (new ZTeraDBQuery("product"))
->select()
->fields(["name" => 1, "price" => 1])
->filter(["status" => "A"])
->sort(["price" => 1])
->limit(0, 20);
π Common Mistakes
β Using filterCondition for simple equalities
β Use .filter() unless you need complex logic
β Forgetting .fields() with insert/update
β Always set fields before inserts/updates
β Wrong sort values
β Use only 1 or -1
β Using SELECT without schemaName
β Always pass valid schema to constructor
π Youβre Ready for Filtering Logic!
Continue to:
π filter-condition.md