syswd/query-builder

此包已被废弃且不再维护。未建议替代包。

PHP 的快速、简单、无依赖查询构建器。

1.0.1 2024-07-29 12:35 UTC

This package is not auto-updated.

Last update: 2024-07-29 13:04:13 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
$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' ]);

条件

如果方法不以 "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');

条件(上述所有方法)也可以接受 Closure 作为第一个参数。这可以创建子条件。子条件将通过使用的方法与主查询连接。匿名函数的参数是嵌套的 Criteria 对象,允许您使用上述所有 where() 方法。

$qbf->where(function ($query) {
    $query->where('id', 1)
        ->whereNot('status', 2);
});

条件也可以接受两种方式作为第一个参数的原始查询部分。第一种 - 所有完整条件(列名、运算符和值),或仅列/表列值作为第一个参数,值作为第二个。

$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');
  • 全文搜索