“XOOPS查询生成器”
XOOPS查询生成器提供了一个现代、流畅的界面来构建SQL查询。它有助于防止SQL注入,提高可读性,并为多个数据库系统提供数据库抽象。
查询生成器架构
Section titled “查询生成器架构”graph TD A[QueryBuilder] -->|builds| B[SELECT Queries] A -->|builds| C[INSERT Queries] A -->|builds| D[UPDATE Queries] A -->|builds| E[DELETE Queries]
F[Table] -->|chains| G[select] F -->|chains| H[where] F -->|chains| I[orderBy] F -->|chains| J[limit]
G -->|chains| K[join] G -->|chains| H H -->|chains| I I -->|chains| J
L[Execute Methods] -->|returns| M[Results] L -->|returns| N[Count] L -->|returns| O[First/Last]查询生成器类
Section titled “查询生成器类”具有流畅界面的主要查询构建器类。
namespace Xoops\Database;
class QueryBuilder{ protected string $table = ''; protected string $type = 'SELECT'; protected array $selects = []; protected array $joins = []; protected array $wheres = []; protected array $orders = []; protected int $limit = 0; protected int $offset = 0; protected array $bindings = [];}####表
为表创建新的查询生成器。
public static function table(string $table): QueryBuilder参数:
| 参数 | 类型 | 描述 |
|---|---|---|
$table | 字符串 | 表名(带或不带前缀) |
返回: QueryBuilder - 查询构建器实例
示例:
$query = QueryBuilder::table('users');$query = QueryBuilder::table('xoops_users'); // With prefixSELECT 查询
Section titled “SELECT 查询”指定要选择的列。
public function select(...$columns): self参数:
| 参数 | 类型 | 描述 |
|---|---|---|
...$columns | 数组 | 列名或表达式 |
返回: self - 用于方法链接
示例:
// Simple selectQueryBuilder::table('users') ->select('id', 'username', 'email') ->get();
// Select with aliasesQueryBuilder::table('users') ->select('id as user_id', 'username as name') ->get();
// Select all columnsQueryBuilder::table('users') ->select('*') ->get();
// Select with expressionsQueryBuilder::table('orders') ->select('id', 'COUNT(*) as total_items') ->groupBy('id') ->get();添加 WHERE 条件。
public function where(string $column, string $operator = '=', mixed $value = null): self参数:
| 参数 | 类型 | 描述 |
|---|---|---|
$column | 字符串 | 栏目名称 |
$operator | 字符串 | 比较运算符 |
$value | 混合 | 比较价值 |
返回: self - 用于方法链接
运营商:
| 操作员 | 描述 | 示例 |
|---|---|---|
= | 平等 | ->where('status', '=', 'active') |
!= 或 <> | 不等于 | ->where('status', '!=', 'deleted') |
> | 大于 | ->where('price', '>', 100) |
< | 小于 | ->where('price', '<', 100) |
>= | 大于或等于 | ->where('age', '>=', 18) |
<= | 小于或等于 | ->where('age', '<=', 65) |
LIKE | 模式匹配 | ->where('name', 'LIKE', '%john%') |
IN | 在列表中 | ->where('status', 'IN', ['active', 'pending']) |
NOT IN | 不在列表中 | ->where('id', 'NOT IN', [1, 2, 3]) |
BETWEEN | 范围 | ->where('age', 'BETWEEN', [18, 65]) |
IS NULL | 为空 | ->where('deleted_at', 'IS NULL') |
IS NOT NULL | 不为空 | ->where('deleted_at', 'IS NOT NULL') |
示例:
// Single conditionQueryBuilder::table('users') ->select('*') ->where('status', '=', 'active') ->get();
// Multiple conditions (AND)QueryBuilder::table('users') ->select('*') ->where('status', '=', 'active') ->where('age', '>=', 18) ->get();
// IN operatorQueryBuilder::table('products') ->select('*') ->where('category_id', 'IN', [1, 2, 3]) ->get();
// LIKE operatorQueryBuilder::table('users') ->select('*') ->where('email', 'LIKE', '%@example.com') ->get();
// NULL checkQueryBuilder::table('users') ->select('*') ->where('deleted_at', 'IS NULL') ->get();添加 OR 条件。
public function orWhere(string $column, string $operator = '=', mixed $value = null): self示例:
QueryBuilder::table('users') ->select('*') ->where('status', '=', 'active') ->orWhere('premium', '=', 1) ->get(); // SELECT * FROM users WHERE status = 'active' OR premium = 1whereIn / whereNotIn
Section titled “whereIn / whereNotIn”IN/NOT IN 的便捷方法。
public function whereIn(string $column, array $values): selfpublic function whereNotIn(string $column, array $values): self示例:
QueryBuilder::table('posts') ->select('*') ->whereIn('status', ['published', 'scheduled']) ->get();
QueryBuilder::table('comments') ->select('*') ->whereNotIn('spam_score', [8, 9, 10]) ->get();whereNull / whereNotNull
Section titled “whereNull / whereNotNull”NULL检查的便捷方法。
public function whereNull(string $column): selfpublic function whereNotNull(string $column): self示例:
QueryBuilder::table('users') ->select('*') ->whereNotNull('verified_at') ->get();检查值是否在两个值之间。
public function whereBetween(string $column, array $values): self示例:
QueryBuilder::table('products') ->select('*') ->whereBetween('price', [10, 100]) ->get();
QueryBuilder::table('orders') ->select('*') ->whereBetween('created_at', ['2024-01-01', '2024-12-31']) ->get();###加入
添加 INNER JOIN。
public function join( string $table, string $first, string $operator = '=', string $second = null): self示例:
QueryBuilder::table('posts') ->select('posts.*', 'users.username', 'categories.name') ->join('users', 'posts.user_id', '=', 'users.id') ->join('categories', 'posts.category_id', '=', 'categories.id') ->where('posts.published', '=', 1) ->get();左连接/右连接
Section titled “左连接/右连接”替代连接类型。
public function leftJoin( string $table, string $first, string $operator = '=', string $second = null): self
public function rightJoin( string $table, string $first, string $operator = '=', string $second = null): self示例:
QueryBuilder::table('users') ->select('users.*', 'COUNT(posts.id) as post_count') ->leftJoin('posts', 'users.id', '=', 'posts.user_id') ->groupBy('users.id') ->get();按列对结果进行分组。
public function groupBy(...$columns): self示例:
QueryBuilder::table('orders') ->select('user_id', 'COUNT(*) as order_count', 'SUM(total) as total_spent') ->groupBy('user_id') ->get();
QueryBuilder::table('sales') ->select('department', 'region', 'SUM(amount) as total') ->groupBy('department', 'region') ->get();添加 HAVING 条件。
public function having(string $column, string $operator = '=', mixed $value = null): self示例:
QueryBuilder::table('orders') ->select('user_id', 'COUNT(*) as order_count') ->groupBy('user_id') ->having('order_count', '>', 5) ->get();订单结果。
public function orderBy(string $column, string $direction = 'ASC'): self参数:
| 参数 | 类型 | 描述 |
|---|---|---|
$column | 字符串 | 排序依据 |
$direction | 字符串 | ASC 或 DESC |
示例:
// Single orderQueryBuilder::table('users') ->select('*') ->orderBy('created_at', 'DESC') ->get();
// Multiple ordersQueryBuilder::table('posts') ->select('*') ->orderBy('category_id', 'ASC') ->orderBy('created_at', 'DESC') ->get();
// Random orderQueryBuilder::table('quotes') ->select('*') ->orderBy('RAND()') ->get();限制和抵消结果。
public function limit(int $limit): selfpublic function offset(int $offset): self示例:
// Simple limitQueryBuilder::table('posts') ->select('*') ->limit(10) ->get();
// Pagination$page = 2;$perPage = 20;$offset = ($page - 1) * $perPage;
QueryBuilder::table('posts') ->select('*') ->limit($perPage) ->offset($offset) ->get();执行查询并返回所有结果。
public function get(): array返回: array - 结果行数组
示例:
$users = QueryBuilder::table('users') ->select('id', 'username', 'email') ->where('status', '=', 'active') ->orderBy('username') ->get();
foreach ($users as $user) { echo $user['username'] . ' (' . $user['email'] . ')' . "\n";}得到第一个结果。
public function first(): ?array返回: ?array - 第一行或空
示例:
$user = QueryBuilder::table('users') ->select('*') ->where('id', '=', 123) ->first();
if ($user) { echo 'Found: ' . $user['username'];}得到最后的结果。
public function last(): ?array示例:
$latestPost = QueryBuilder::table('posts') ->select('*') ->orderBy('created_at', 'DESC') ->last();获取结果的计数。
public function count(): int返回: int - 行数
示例:
$activeUsers = QueryBuilder::table('users') ->where('status', '=', 'active') ->count();
echo "Active users: $activeUsers";检查查询是否返回任何结果。
public function exists(): bool返回: bool - 如果结果存在则为 True
示例:
if (QueryBuilder::table('users')->where('email', '=', 'test@example.com')->exists()) { echo 'User already exists';}获取聚合值。
public function aggregate(string $function, string $column): mixed示例:
$maxPrice = QueryBuilder::table('products') ->aggregate('MAX', 'price');
$avgAge = QueryBuilder::table('users') ->aggregate('AVG', 'age');
$totalSales = QueryBuilder::table('orders') ->aggregate('SUM', 'total');INSERT 查询
Section titled “INSERT 查询”###插入
插入一行。
public function insert(array $values): bool```**示例:**```phpQueryBuilder::table('users')->insert([ 'username' => 'john', 'email' => 'john@example.com', 'password' => password_hash('secret', PASSWORD_BCRYPT), 'created_at' => date('Y-m-d H:i:s')]);插入多行。
public function insertMany(array $rows): bool示例:
QueryBuilder::table('log_entries')->insertMany([ ['action' => 'login', 'user_id' => 1, 'timestamp' => time()], ['action' => 'logout', 'user_id' => 2, 'timestamp' => time()], ['action' => 'update', 'user_id' => 3, 'timestamp' => time()]]);UPDATE 查询
Section titled “UPDATE 查询”###更新
更新行。
public function update(array $values): int返回: int - 受影响的行数
示例:
// Update single userQueryBuilder::table('users') ->where('id', '=', 123) ->update([ 'email' => 'newemail@example.com', 'updated_at' => date('Y-m-d H:i:s') ]);
// Update multiple rowsQueryBuilder::table('posts') ->where('status', '=', 'draft') ->where('created_at', '<', date('Y-m-d', strtotime('-30 days'))) ->update([ 'status' => 'archived' ]);增加或减少列。
public function increment(string $column, int $amount = 1): intpublic function decrement(string $column, int $amount = 1): int示例:
// Increment view countQueryBuilder::table('posts') ->where('id', '=', 123) ->increment('views');
// Decrement stockQueryBuilder::table('products') ->where('id', '=', 456) ->decrement('stock', 5);DELETE 查询
Section titled “DELETE 查询”###删除
删除行。
public function delete(): int返回: int - 已删除的行数
示例:
// Delete single recordQueryBuilder::table('comments') ->where('id', '=', 789) ->delete();
// Delete multiple recordsQueryBuilder::table('log_entries') ->where('created_at', '<', date('Y-m-d', strtotime('-30 days'))) ->delete();删除表中的所有行。
public function truncate(): bool示例:
// Clear all sessionsQueryBuilder::table('sessions')->truncate();QueryBuilder::table('products') ->select('id', 'name', QueryBuilder::raw('price * quantity as total')) ->get();$recentPostIds = QueryBuilder::table('posts') ->select('id') ->where('created_at', '>', date('Y-m-d', strtotime('-7 days'))) ->toSql();
$comments = QueryBuilder::table('comments') ->select('*') ->whereIn('post_id', $recentPostIds) ->get();public function toSql(): string示例:
$sql = QueryBuilder::table('users') ->select('id', 'username') ->where('status', '=', 'active') ->toSql();
echo $sql;// SELECT id, username FROM xoops_users WHERE status = ?带有连接的复杂选择
Section titled “带有连接的复杂选择”<?php/** * Get posts with author and category info */
$posts = QueryBuilder::table('posts') ->select( 'posts.id', 'posts.title', 'posts.content', 'posts.created_at', 'users.username as author', 'categories.name as category' ) ->join('users', 'posts.user_id', '=', 'users.id') ->join('categories', 'posts.category_id', '=', 'categories.id') ->where('posts.published', '=', 1) ->orderBy('posts.created_at', 'DESC') ->limit(10) ->get();
foreach ($posts as $post) { echo '<article>'; echo '<h2>' . htmlspecialchars($post['title']) . '</h2>'; echo '<p class="meta">By ' . htmlspecialchars($post['author']) . ' in ' . htmlspecialchars($post['category']) . '</p>'; echo '<p>' . htmlspecialchars($post['content']) . '</p>'; echo '</article>';}使用 QueryBuilder 进行分页
Section titled “使用 QueryBuilder 进行分页”<?php/** * Paginated results */
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;$perPage = 20;$offset = ($page - 1) * $perPage;
// Get total count$total = QueryBuilder::table('articles') ->where('status', '=', 'published') ->count();
// Get page results$articles = QueryBuilder::table('articles') ->select('*') ->where('status', '=', 'published') ->orderBy('created_at', 'DESC') ->limit($perPage) ->offset($offset) ->get();
// Calculate pagination$pages = ceil($total / $perPage);
// Display resultsforeach ($articles as $article) { echo '<div class="article">' . htmlspecialchars($article['title']) . '</div>';}
// Display pagination linksif ($pages > 1) { echo '<nav class="pagination">'; for ($i = 1; $i <= $pages; $i++) { if ($i == $page) { echo '<span class="current">' . $i . '</span>'; } else { echo '<a href="?page=' . $i . '">' . $i . '</a>'; } } echo '</nav>';}使用聚合进行数据分析
Section titled “使用聚合进行数据分析”<?php/** * Sales analysis */
// Total sales by region$regionSales = QueryBuilder::table('orders') ->select('region', QueryBuilder::raw('SUM(total) as total_sales'), QueryBuilder::raw('COUNT(*) as order_count')) ->groupBy('region') ->orderBy('total_sales', 'DESC') ->get();
foreach ($regionSales as $region) { echo $region['region'] . ': $' . number_format($region['total_sales'], 2) . ' (' . $region['order_count'] . ' orders)' . "\n";}
// Average order value$avgOrderValue = QueryBuilder::table('orders') ->aggregate('AVG', 'total');
echo 'Average order value: $' . number_format($avgOrderValue, 2);- 使用参数化查询 - QueryBuilder 自动处理参数绑定
- 链方法 - 利用流畅的接口来获得可读的代码
- 测试SQL输出 - 使用
toSql()验证生成的查询 - 使用索引 - 确保经常查询的列被索引
- 限制结果 - 对于大型数据集始终使用
limit() - 使用聚合 - 让数据库执行counting/summing而不是PHP
- 转义输出 - 始终使用
htmlspecialchars()转义显示的数据 - 索引性能 - 监控慢速查询并进行相应优化
- XOOPSDatabase - 数据库层和连接
- 标准 - 旧标准-based查询系统
- ../Core/XOOPSObject - 数据对象持久性
- ../Module/Module-System - 模区块数据库操作