api-skeletons/zf-doctrine-orm-querybuilder

This package is abandoned and no longer maintained. The author suggests using the zfcampus/zf-doctrine-querybuilder package instead.

ORM QueryBuilder filters for Doctrine

1.0.3 2016-08-04 00:24 UTC

This package is not auto-updated.

Last update: 2016-12-02 19:11:26 UTC


README

Build status Total Downloads

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

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 of this module uses composer. For composer documentation, please refer to getcomposer.org.

$ php composer.phar require api-skeletons/zf-doctrine-orm-querybuilder ^1.0

Once installed, add ZF\Doctrine\ORM\QueryBuilder to your list of modules in config/application.config.php.

Configuring the Module

Copy config/zf-doctrine-orm-querybuilder.global.php.dist to config/autoload/zf-doctrine-orm-querybuilder.global.php and edit the list of invokables to those you want enabled.

Use With Apigility Doctrine

The abstract query provider ZF\Doctrine\ORM\QueryBuilder\Query\Provider\AbstractQueryProvider has the function applyFiltersAndOrderBy which will add request filters and order by directives to the QueryBuilder you pass it.

Use

Configuration example

    'zf-doctrine-orm-querybuilder-orderby' => array(
        'invokables' => array(
            'field' => 'ZF\Doctrine\ORM\QueryBuilder\OrderBy\Field',
        ),
    ),
    'zf-doctrine-orm-querybuilder-filter' => array(
        'invokables' => array(
            'eq' => 'ZF\Doctrine\ORM\QueryBuilder\Filter\Equals',
        ),
    ),

A sample Request in PHP syntax.

$_GET = array(
    'filter' => array(
        array(
            'type' => 'eq',
            'field' => 'name',
            'value' => 'Tom',
        ),
    ),
    'order-by' => array(
        array(
            'type' => 'field',
            'field' => 'startAt',
            'direction' => 'desc',
        ),
    ),
);

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.

An example GET query with jQuery

$(function() {
    $.ajax({
        url: "http://localhost:8081/api/resource-name",
        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

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:

    array('type' => 'eq', 'field' => 'group', 'value' => '1')

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:

    array('type' => 'ismemberof', 'field' => 'groups', 'value' => '1')

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

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

Joining Entities and Aliasing Queries

There is an included Filter 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-orm-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:

    array('type' => 'innerjoin', 'field' => 'report', 'alias' => 'r'),
    array('type' => 'eq', 'alias' => 'r', 'field' => 'id', 'value' => '2')

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

    array('type' => 'innerjoin', 'parentAlias' => 'r', 'field' => 'owner', 'alias' => 'o'),

To enable inner join add this to your configuration:

    'zf-doctrine-orm-querybuilder-filter' => array(
        'invokables' => array(
            'innerjoin' => 'ZF\Doctrine\ORM\QueryBuilder\Filter\InnerJoinFilter',
        ),
    ),

Included Filter Types

Equals:

array('type' => 'eq', 'field' => 'fieldName', 'value' => 'matchValue')

Not Equals:

array('type' => 'neq', 'field' => 'fieldName', 'value' => 'matchValue')

Less Than:

array('type' => 'lt', 'field' => 'fieldName', 'value' => 'matchValue')

Less Than or Equals:

array('type' => 'lte', 'field' => 'fieldName', 'value' => 'matchValue')

Greater Than:

array('type' => 'gt', 'field' => 'fieldName', 'value' => 'matchValue')

Greater Than or Equals:

array('type' => 'gte', 'field' => 'fieldName', 'value' => 'matchValue')

Is Null:

array('type' => 'isnull', 'field' => 'fieldName')

Is Not Null:

array('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:

array('type' => 'in', 'field' => 'fieldName', 'values' => array(1, 2, 3))

NotIn:

array('type' => 'notin', 'field' => 'fieldName', 'values' => array(1, 2, 3))

Between:

array('type' => 'between', 'field' => 'fieldName', 'from' => 'startValue', 'to' => 'endValue')

Like (% is used as a wildcard):

array('type' => 'like', 'field' => 'fieldName', 'value' => 'like%search')

Is Member Of:

array('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.

array(
    'type' => 'andx',
    'conditions' => array(
        array('field' =>'name', 'type'=>'eq', 'value' => 'ArtistOne'),
        array('field' =>'type', 'type'=>'eq', 'value' => 'Band'),
    ),
    '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.

array(
    'type' => 'orx',
    'conditions' => array(
        array('field' =>'name', 'type'=>'eq', 'value' => 'ArtistOne'),
        array('field' =>'name', 'type'=>'eq', 'value' => 'ArtistTwo'),
    ),
    'where' => 'and'
)

Included Order By Type

Field:

array('type' => 'field', 'field' => 'fieldName', 'direction' => 'desc');