requtize / query-builder
PHP快速、简单、无依赖的查询构建器。
1.0.1
2019-01-06 14:25 UTC
Requires
- php: ~5.5 || ^7.0
Requires (Dev)
- mockery/mockery: 0.9.4
- phpunit/phpunit: ^4.8
This package is auto-updated.
Last update: 2024-09-12 14:00:05 UTC
README
查询构建器是一个快速、简单、方法链、无依赖的库,用于创建SQL查询,简单快速地编写、扩展和管理。支持PDO支持的所有数据库。也可以用作数据库抽象层。
安装 - 通过 composer.json
"requtize/query-builder": "dev-master"
在已建立连接的情况下使用,在其他系统的某个部分。
use Requtize\QueryBuilder\Connection; use Requtize\QueryBuilder\QueryBuilder\QueryBuilderFactory; use Requtize\QueryBuilder\ConnectionAdapters\PdoBridge; // Somewhere in our application we have created PDO instance $pdo = new PDO('dns...'); // Build Connection object with PdoBridge ad Adapter $conn = new Connection(new PdoBridge($pdo)); // Pass this connection to Factory $qbf = new QueryBuilderFactory($conn); // Now we can use the factory as QueryBuilder - it creates QueryBuilder // object every time we use some of method from QueryBuilder and returns it. $result = $qbf->from('table')->where('cost', '>', 120)->all();
查询构建器方法
表选择
// Set table to operate on. $qbf->table('table'); $qbf->table('table', 'next-table'); $qbf->table('table', 'next-table', 'and-another'); $qbf->table([ 'table', 'next-table', 'and-another' ]); // Alias to table() method. $qbf->from(...);
Selects
// Selects $qbf->select('*'); $qbf->select('column'); $qbf->select('column1', 'column2', 'column3'); $qbf->select([ 'column1', 'column2', 'column3' ]); // Select DISTINCT $qbf->selectDistinct('*'); $qbf->selectDistinct('column'); $qbf->selectDistinct('column1', 'column2', 'column3'); $qbf->selectDistinct([ 'column1', 'column2', 'column3' ]);
Wheres
如果方法不以 "or*" 开头,多次调用将将其连接为 "AND"。
$qbf->where('name', 'Adam') ->where('name', '=', 'Adam') ->orWhere('name', 'Adam') ->orWhere('name', '=', 'Adam') ->whereNot('name', 'Adam') ->whereNot('name', '=', 'Adam') ->orWhereNot('name', 'Adam') ->orWhereNot('name', '=', 'Adam') ->whereIn('name' [ 'Adam', 'Eva' ]) ->whereNotIn('name' [ 'Adam', 'Eva' ]) ->orWhereIn('name' [ 'Adam', 'Eva' ]) ->orWhereNotIn('name' [ 'Adam', 'Eva' ]) ->whereBetween('age', 10, 20) ->orWhereBetween('age', 10, 20) ->whereNull('sex') ->whereNotNull('sex') ->orWhereNull('sex') ->orWhereNotNull('sex');
Wheres(上述所有方法)也可以将闭包作为第一个参数。这可以创建子标准。子标准将使用使用的方法连接到主查询。匿名函数的参数是对象 NestedCriteria,它允许您使用上述所有 where() 方法。
$qbf->where(function ($query) { $query->where('id', 1) ->whereNot('status', 2); });
Wheres也可以将作为第一个参数的原始查询部分以两种方式接受。首先 - 所有完整标准(列名、运算符和值),或仅列/表列值作为第一个参数,值作为第二个。
$qbf->where($qbf->raw('name'), 'Adam'); $qbf->where($qbf->raw('name = "Adam"'));
连接
// Simple INNER JOIN $qbf->join('table', 'name', '=', 'Adam', 'inner') // INNER JOIN as Closure with advanced ON criteria ->join('table', function ($join) { $join->on('name', 'Adam') ->on('name', '=', 'Adam') ->orOn('name', 'Adam') ->orOn('name', '=', 'Adam'); }) ->leftJoin('table', 'name', '=', 'Adam') ->leftJoin('table', function ($join) { // ... }) ->rightJoin('table', 'name', '=', 'Adam') ->rightJoin('table', function ($join) { // ... }) ->innerJoin('table', 'name', '=', 'Adam') ->innerJoin('table', function ($join) { // ... });
结果集
$qbf->all(); // Returns all results. $qbf->first(); // Returns first result. $qbf->count($column); $qbf->max($column); $qbf->min($column); $qbf->sum($column); $qbf->avg($column);
插入
$qbf->from('table')->insert([ 'name' => 'Adam' ]); $qbf->insert([ 'name' => 'Adam' ], 'table'); $qbf->from('table')->insertIgnore([ 'name' => 'Adam' ]); $qbf->insertIgnore([ 'name' => 'Adam' ], 'table'); $qbf->from('table')->replace([ 'id' => 12, 'name' => 'Adam' ]); $qbf->replace([ 'id' => 12, 'name' => 'Adam' ], 'table');
如果插入调用操作具有 AUTO_INCREMENT 列的表,则方法将返回行的插入 ID。您还可以使用其他方法(在调用 insert()
方法之后)来完成相同的事情
$qbf->getLastId();
更新
$qbf ->from('table') ->where('name', 'John') ->update([ 'name' => 'Adam' ]); $qbf ->where('name', 'John') ->update([ 'name' => 'Adam' ], 'table'); $qbf ->from('table') ->where('name', 'John') ->updateOrInsert([ 'name' => 'Adam' ]); $qbf ->where('name', 'John') ->updateOrInsert([ 'name' => 'Adam' ], 'table');
删除
$qbf ->where('name', 'Adam') ->delete('table'); $qbf ->from('table') ->where('name', 'Adam') ->delete();
原始值
在大多数方法和参数中,您可以将原始值作为参数传递。为此,您只需要使用 raw() 方法,并将此方法的输出传递给任何您想要的参数。
$qbf->where($qbf->raw('name'), $qbf->raw('Adam')); $qbf->select($qbf->raw('name')); $qbf->table($qbf->raw('table')); // ...and so on...
原始查询
// SELECT Query. $rows = $qbf->query('SELECT * FROM table WHERE name = :name', [ ':name' => 'Adam' ]); // UPDATE, INSERT, DELETE, etc. $affectedCount = $qbf->exec('UPDATE table SET id = :id WHERE name = :name', [ ':id' => 15, ':name' => 'Adam' ]);
子查询和嵌套查询
在某些情况下,您可能需要创建子查询以提供某些特殊功能。使用 subQuery() 方法来完成此操作。使用示例
$subQuery = $qbf ->select('name') ->from('persons') ->where('id', 15); $query = $qbf ->select('table.*') ->from('table') ->select($qbf->subQuery($subQuery, 'alias1')); $nestedQuery = $qbf ->select('*') ->from($qbf->subQuery($query, 'alias2'));
查询构建器生成的查询。
SELECT * FROM ( SELECT `table`.*, ( SELECT `name` FROM `persons` WHERE `id` = 15 ) AS alias1 FROM `table` ) AS alias2
获取编译后的查询
如果您想在执行之前预览查询或用于调试意图,则可能希望使用 getQuery() 方法,该方法返回包含编译后的查询(带占位符)、绑定数组和 PDO 实例的 Query 对象。此对象包含当前 Query Builder 实例的所有数据。
$qbf->getQuery($type = 'select', array $parameters = []);
#API
// Returns passed PDO object. $qbf->getPdo(); // Returns all Query Segments created in this instance of Query Builder $qbf->getQuerySegments(); // Or only selected segment $qbf->getQuerySegment('where'); // Sets and gets EventDispatcher $qbf->getEventDispatcher(); $qbf->setEventDispatcher(Requtize\QueryBuilder\Event\EventDispatcherInterface $eventDispatcher); // Sets FetchMode for PDO. IF PDOs Fetch Mode requires many arguments, just pass this to this method as next arguments. $qbf->setFetchMode($mode...); // Sets Fetch mode to Object. $qbf->asObject($className, $classConstructorArgs = []); // Gets and sets DB connection object. $qbf->setConnection(Requtize\QueryBuilder\Connection $connection); $qbf->getConnection(); // Gets Db schema $qbf->getSchema(); // Create new QueryBuilder instance. $qbf->newQuery(Requtize\QueryBuilder\Connection $connection = null); // Forks query. Copies all Query Segments, settings to new object and returns new object. Allows to create new Query, but with earlier defined criterias. $qbf->forkQuery();
@todo
- Where LIKE
$qb->like('column', 'value'); // WHERE column LIKE '%value%' $qb->like('column', 'value', 'left|start'); // WHERE column LIKE '%value' $qb->like('column', 'value', 'right|end'); // WHERE column LIKE 'value%'
- 作用域 - 可重用的预定义语句组。
$scopes = new ScopesContainer; $scopes->register('scope-name', function($qb, $arg1, $arg2) { if($arg1) $qb->where('add_date', '<', 'NOW()'); if($arg2) $qb->where('add_date', '>=', 'NOW()'); }); $qbf->setScopes($scopes); // ... $qbf->from('table')->scopeName('arg1', 'arg2')->all();
- 返回的行块必须在未定义 LIMIT 语句的情况下才能正常工作!
$qb->where('column', 1)->chunk(30, function (array $chunk) { foreach($chunk as $row) { // Do something with $row... } });
- 将数据作为聚合集合插入
$qb->insert([ [ 'id' => 1, 'col' => 'val' ], [ 'id' => 1, 'col' => 'val' ], [ 'id' => 1, 'col' => 'val' ], [ 'id' => 1, 'col' => 'val' ] ], true, 'table');
- 全文搜索