PHPackages                             jackdpeterson/psr7-doctrine-querybuilder - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. jackdpeterson/psr7-doctrine-querybuilder

AbandonedLibrary[Database &amp; ORM](/categories/database)

jackdpeterson/psr7-doctrine-querybuilder
========================================

PSR-7 Doctrine QueryBuilder module -- manipulate a Doctrine Query Builder instance with the $args from your PSR-7 requests

1.5.1(9y ago)0641BSD-3-ClausePHPPHP ^5.6 || ^7.0

Since Jan 22Pushed 8y ago1 watchersCompare

[ Source](https://github.com/jackdpeterson/psr7-doctrine-querybuilder)[ Packagist](https://packagist.org/packages/jackdpeterson/psr7-doctrine-querybuilder)[ Docs](https://apigility.org)[ RSS](/packages/jackdpeterson-psr7-doctrine-querybuilder/feed)WikiDiscussions master Synced today

READMEChangelogDependencies (17)Versions (21)Used By (0)

PSR-7 Doctrine QueryBuilder (Forked from ZF-Doctrine-QueryBuilder)
==================================================================

[](#psr-7-doctrine-querybuilder-forked-from-zf-doctrine-querybuilder)

This library provides query builder directives from array parameters. This library was designed to apply filters from an HTTP request to give an API fluent filter and order-by dialects.

Philosophy
----------

[](#philosophy)

Given developers identified A and B: A == B with respect to ability and desire to filter and sort the entity data.

The Doctrine entity to share contains

```
id integer,
name string,
startAt datetime,
endAt datetime,

```

Developer A or B writes the API. The resource is a single Doctrine Entity and the data is queried using a Doctrine QueryBuilder `$objectManager->createQueryBuilder()`. This module gives the other developer the same filtering and sorting ability to the Doctrine query builder, but accessed through request parameters, as the API author. For instance, `startAt between('2015-01-09', '2015-01-11');` and `name like ('%arlie')`are not common API filters for hand rolled APIs and perhaps without this module the API author would choose not to implement it for their reason(s). With the help of this module the API developer can implement complex queryability to resources without complicated effort thereby maintaining A == B.

Installation
------------

[](#installation)

Installation of this module uses composer. For composer documentation, please refer to [getcomposer.org](http://getcomposer.org/).

```
$ composer require jackdpeterson/psr7-doctrine-querybuilder
```

Once installed, add `jackdpeterson\Doctrine\QueryBuilder` to your list of modules inside `config/application.config.php`.

> ### zf-component-installer
>
> [](#zf-component-installer)
>
> If you use [zf-component-installer](https://github.com/zendframework/zf-component-installer), that plugin will install zf-doctrine-querybuilder as a module for you.

Configuring the Module
----------------------

[](#configuring-the-module)

Copy `config/zf-doctrine-querybuilder.global.php.dist` to `config/autoload/zf-doctrine-querybuilder.global.php`and edit the list of aliases for orm and odm to those you want enabled by default.

Use With Slim Framework
-----------------------

[](#use-with-slim-framework)

To enable all filters you may override the default query providers in `zf-apigility-doctrine`. Add this to your `zf-doctrine-querybuilder.global.php` config file and filters and order-by will be applied if they are in `$_GET['filter']` or `$_GET['order-by']` request. These `$_GET` keys are customizable through `zf-doctrine-querybuilder-options`:

```
'zf-apigility-doctrine-query-provider' => [
    'aliases' => [
        'default_orm' => \jackdpeterson\Doctrine\QueryBuilder\Query\Provider\DefaultOrm::class,
        'default_odm' => \jackdpeterson\Doctrine\QueryBuilder\Query\Provider\DefaultOdm::class,
    ],
    'factories' => [
        \jackdpeterson\Doctrine\QueryBuilder\Query\Provider\DefaultOrm::class => \jackdpeterson\Doctrine\QueryBuilder\Query\Provider\DefaultOrmFactory::class,
        \jackdpeterson\Doctrine\QueryBuilder\Query\Provider\DefaultOdm::class => \jackdpeterson\Doctrine\QueryBuilder\Query\Provider\DefaultOdmFactory::class,
    ],
],
```

Use
---

[](#use)

Configuration example

```
'zf-doctrine-querybuilder-orderby-orm' => [
    'aliases' => [
        'field' => \jackdpeterson\Doctrine\QueryBuilder\OrderBy\ORM\Field::class,
    ],
    'factories' => [
        \jackdpeterson\Doctrine\QueryBuilder\OrderBy\ORM\Field::class => \Zend\ServiceManager\Factory\InvokableFactory::class,
    ],
],
'zf-doctrine-querybuilder-filter-orm' => [
    'aliases' => [
        'eq' => \jackdpeterson\Doctrine\QueryBuilder\Filter\ORM\Equals::class,
    ],
    'factories' => [
        \jackdpeterson\Doctrine\QueryBuilder\Filter\ORM\Equals::class => \Zend\ServiceManager\Factory\InvokableFactory::class,
    ],
],
```

Request example

```
$_GET = [
    'filter' => [
        [
            'type'  => 'eq',
            'field' => 'name',
            'value' => 'Tom',
        ],
    ],
    'order-by' => [
        [
            'type'      => 'field',
            'field'     => 'startAt',
            'direction' => 'desc',
        ],
    ],
];
```

Resource example

```
$serviceLocator = $this->getApplication()->getServiceLocator();
$objectManager = $serviceLocator->get('doctrine.entitymanager.orm_default');

$filterManager = $serviceLocator->get('ZfDoctrineQueryBuilderFilterManagerOrm');
$orderByManager = $serviceLocator->get('ZfDoctrineQueryBuilderOrderByManagerOrm');

$queryBuilder = $objectManager->createQueryBuilder();
$queryBuilder->select('row')
    ->from($entity, 'row')
;

$metadata = $objectManager->getMetadataFactory()->getMetadataFor(ENTITY_NAME); // $e->getEntity() using doctrine resource event
$filterManager->filter($queryBuilder, $metadata, $_GET['filter']);
$orderByManager->orderBy($queryBuilder, $metadata, $_GET['order-by']);

$result = $queryBuilder->getQuery()->getResult();
```

Filters
-------

[](#filters)

Filters are not simple key/value pairs. Filters are a key-less array of filter definitions. Each filter definition is an array and the array values vary for each filter type.

Each filter definition requires at a minimum a 'type'. A type references the configuration key such as 'eq', 'neq', 'between'.

Each filter definition requires at a minimum a 'field'. This is the name of a field on the target entity.

Each filter definition may specify 'where' with values of either 'and', 'or'.

Embedded logic such as and(x or y) is supported through AndX and OrX filter types.

### Building HTTP GET query:

[](#building-http-get-query)

Javascript Example:

```
$(function () {
    $.ajax({
        url: "http://localhost:8081/api/db/entity/user_data",
        type: "GET",
        data: {
            'filter': [
                {
                    'field': 'cycle',
                    'where': 'or',
                    'type': 'between',
                    'from': '1',
                    'to': '100'
                },
                {
                    'field': 'cycle',
                    'where': 'or',
                    'type': 'gte',
                    'value': '1000'
                }
            ]
        },
        dataType: "json"
    });
});
```

Querying Relations
------------------

[](#querying-relations)

### Single valued

[](#single-valued)

It is possible to query collections by relations - just supply the relation name as `fieldName` and identifier as `value`.

Assuming we have defined 2 entities, `User` and `UserGroup`...

```
/**
 * @Entity
 */
class User {
    /**
     * @ManyToOne(targetEntity="UserGroup")
     * @var UserGroup
     */
    protected $group;
}
```

```
/**
 * @Entity
 */
class UserGroup {}
```

find all users that belong to UserGroup id #1 by querying the user resource with the following filter:

```
['type' => 'eq', 'field' => 'group', 'value' => '1']
```

### Collection valued

[](#collection-valued)

To match entities A that have entity B in a collection use `ismemberof`. Assuming `User` has a ManyToMany (or OneToMany) association with `UserGroup`...

```
/**
 * @Entity
 */
class User {
    /**
     * @ManyToMany(targetEntity="UserGroup")
     * @var UserGroup[]|ArrayCollection
     */
    protected $groups;
}
```

find all users that belong to UserGroup id #1 by querying the user resource with the following filter:

```
['type' => 'ismemberof', 'field' => 'groups', 'value' => '1']
```

Format of Date Fields
---------------------

[](#format-of-date-fields)

When a date field is involved in a filter you may specify the format of the date using PHP date formatting options. The default date format is `Y-m-d H:i:s` If you have a date field which is just `Y-m-d`, then add the format to the filter. For complete date format options see [DateTime::createFromFormat](http://php.net/manual/en/datetime.createfromformat.php)

```
[
    'format' => 'Y-m-d',
    'value' => '2014-02-04',
]
```

Joining Entities and Aliasing Queries
-------------------------------------

[](#joining-entities-and-aliasing-queries)

There is an included ORM Query Type for Inner Join so for every filter type there is an optional `alias`. The default alias is 'row' and refers to the entity at the heart of the REST resource. There is not a filter to add other entities to the return data. That is, only the original target resource, by default 'row', will be returned regardless of what filters or order by are applied through this module.

Inner Join is not included by default in the `zf-doctrine-querybuilder.global.php.dist`.

This example joins the report field through the inner join already defined on the row entity then filters for `r.id = 2`:

```
    ['type' => 'innerjoin', 'field' => 'report', 'alias' => 'r'],
    ['type' => 'eq', 'alias' => 'r', 'field' => 'id', 'value' => '2']
```

You can inner join tables from an inner join using `parentAlias`:

```
    ['type' => 'innerjoin', 'parentAlias' => 'r', 'field' => 'owner', 'alias' => 'o'],
```

To enable inner join add this to your configuration.

```
'zf-doctrine-querybuilder-filter-orm' => [
    'aliases' => [
        'innerjoin' => \jackdpeterson\Doctrine\QueryBuilder\Filter\ORM\InnerJoin::class,
    ],
    'factories' => [
        \jackdpeterson\Doctrine\QueryBuilder\Filter\ORM\InnerJoin => \Zend\ServiceManager\Factory\InvokableFactory::class,
    ],
],
```

Included Filter Types
---------------------

[](#included-filter-types)

### ORM and ODM

[](#orm-and-odm)

Equals:

```
['type' => 'eq', 'field' => 'fieldName', 'value' => 'matchValue']
```

Not Equals:

```
['type' => 'neq', 'field' => 'fieldName', 'value' => 'matchValue']
```

Less Than:

```
['type' => 'lt', 'field' => 'fieldName', 'value' => 'matchValue']
```

Less Than or Equals:

```
['type' => 'lte', 'field' => 'fieldName', 'value' => 'matchValue']
```

Greater Than:

```
['type' => 'gt', 'field' => 'fieldName', 'value' => 'matchValue']
```

Greater Than or Equals:

```
['type' => 'gte', 'field' => 'fieldName', 'value' => 'matchValue']
```

Is Null:

```
['type' => 'isnull', 'field' => 'fieldName']
```

Is Not Null:

```
['type' => 'isnotnull', 'field' => 'fieldName']
```

Note: Dates in the In and NotIn filters are not handled as dates. It is recommended you use multiple Equals statements instead of these filters for date datatypes.

In:

```
['type' => 'in', 'field' => 'fieldName', 'values' => [1, 2, 3]]
```

NotIn:

```
['type' => 'notin', 'field' => 'fieldName', 'values' => [1, 2, 3]]
```

Between:

```
['type' => 'between', 'field' => 'fieldName', 'from' => 'startValue', 'to' => 'endValue']
```

Like (`%` is used as a wildcard):

```
['type' => 'like', 'field' => 'fieldName', 'value' => 'like%search']
```

### ORM Only

[](#orm-only)

Is Member Of:

```
['type' => 'ismemberof', 'field' => 'fieldName', 'value' => 1]
```

AndX:

In AndX queries, the `conditions` is an array of filter types for any of those described here. The join will always be `and` so the `where` parameter inside of conditions is ignored. The `where` parameter on the AndX filter type is not ignored.

```
[
    'type' => 'andx',
    'conditions' => [
        ['field' =>'name', 'type'=>'eq', 'value' => 'ArtistOne'],
        ['field' =>'name', 'type'=>'eq', 'value' => 'ArtistTwo'],
    ],
    'where' => 'and',
]
```

OrX:

In OrX queries, the `conditions` is an array of filter types for any of those described here. The join will always be `or` so the `where` parameter inside of conditions is ignored. The `where` parameter on the OrX filter type is not ignored.

```
[
    'type' => 'orx',
    'conditions' => [
        ['field' =>'name', 'type'=>'eq', 'value' => 'ArtistOne'],
        ['field' =>'name', 'type'=>'eq', 'value' => 'ArtistTwo'],
    ],
    'where' => 'and',
]
```

### ODM Only

[](#odm-only)

Regex:

```
['type' => 'regex', 'field' => 'fieldName', 'value' => '/.*search.*/i']
```

Included Order By Type
----------------------

[](#included-order-by-type)

Field:

```
['type' => 'field', 'field' => 'fieldName', 'direction' => 'desc']
```

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity9

Limited adoption so far

Community20

Small or concentrated contributor base

Maturity67

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~39 days

Recently: every ~67 days

Total

18

Last Release

3466d ago

Major Versions

0.1.2 → 1.0.02015-05-22

PHP version history (3 changes)0.1.0PHP &gt;=5.3.23

1.4.0PHP &gt;=5.4

1.5.0PHP ^5.6 || ^7.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/e3feb4d99b0a9a91f767bb35c5d46bfd52291ca8f58b5ca8ba8245d5a402bec7?d=identicon)[jackdpeterson](/maintainers/jackdpeterson)

---

Top Contributors

[![TomHAnderson](https://avatars.githubusercontent.com/u/493920?v=4)](https://github.com/TomHAnderson "TomHAnderson (130 commits)")[![michalbundyra](https://avatars.githubusercontent.com/u/7423207?v=4)](https://github.com/michalbundyra "michalbundyra (46 commits)")[![veewee](https://avatars.githubusercontent.com/u/1618158?v=4)](https://github.com/veewee "veewee (42 commits)")[![weierophinney](https://avatars.githubusercontent.com/u/25943?v=4)](https://github.com/weierophinney "weierophinney (13 commits)")[![jguittard](https://avatars.githubusercontent.com/u/5320213?v=4)](https://github.com/jguittard "jguittard (7 commits)")[![Hounddog](https://avatars.githubusercontent.com/u/1188248?v=4)](https://github.com/Hounddog "Hounddog (6 commits)")[![zluiten](https://avatars.githubusercontent.com/u/1336070?v=4)](https://github.com/zluiten "zluiten (5 commits)")[![fabio-paiva-sp](https://avatars.githubusercontent.com/u/2126528?v=4)](https://github.com/fabio-paiva-sp "fabio-paiva-sp (4 commits)")[![pietervogelaar](https://avatars.githubusercontent.com/u/1067483?v=4)](https://github.com/pietervogelaar "pietervogelaar (4 commits)")[![iansltx](https://avatars.githubusercontent.com/u/472804?v=4)](https://github.com/iansltx "iansltx (4 commits)")[![jackdpeterson](https://avatars.githubusercontent.com/u/938961?v=4)](https://github.com/jackdpeterson "jackdpeterson (4 commits)")[![Thinkscape](https://avatars.githubusercontent.com/u/270528?v=4)](https://github.com/Thinkscape "Thinkscape (3 commits)")[![lweijl](https://avatars.githubusercontent.com/u/1135396?v=4)](https://github.com/lweijl "lweijl (3 commits)")[![neeckeloo](https://avatars.githubusercontent.com/u/1768645?v=4)](https://github.com/neeckeloo "neeckeloo (3 commits)")[![baptistemanson](https://avatars.githubusercontent.com/u/5444992?v=4)](https://github.com/baptistemanson "baptistemanson (2 commits)")[![mrVrAlex](https://avatars.githubusercontent.com/u/633883?v=4)](https://github.com/mrVrAlex "mrVrAlex (2 commits)")[![serhiikushch](https://avatars.githubusercontent.com/u/1597171?v=4)](https://github.com/serhiikushch "serhiikushch (1 commits)")[![PowerKiKi](https://avatars.githubusercontent.com/u/72603?v=4)](https://github.com/PowerKiKi "PowerKiKi (1 commits)")[![matwright](https://avatars.githubusercontent.com/u/4989280?v=4)](https://github.com/matwright "matwright (1 commits)")[![fabiocarneiro](https://avatars.githubusercontent.com/u/1375034?v=4)](https://github.com/fabiocarneiro "fabiocarneiro (1 commits)")

---

Tags

apidoctrinezendfilterzfapigility

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/jackdpeterson-psr7-doctrine-querybuilder/health.svg)

```
[![Health](https://phpackages.com/badges/jackdpeterson-psr7-doctrine-querybuilder/health.svg)](https://phpackages.com/packages/jackdpeterson-psr7-doctrine-querybuilder)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
