PostgreSQL 9.4 introduced the new data type jsonb. With it some documented operators such as ->, ->> and #>>{} are available to access or retrieve values within a jsonb column data. Since Symfony uses Doctrine as default and Doctrine uses its own query language DQL, the operators aren't available natively. You can also visit PostgreSQL json function and operator documentation to check which operator you expect to use.
This bundle adds some custom functions to allow developers to use such operators.
- Installation
- Adding custom functions to config.yml
- Documentation
- Planned improvements
Open a command console, enter your project directory and execute the following command to download the latest stable version of this bundle:
$ composer require fabianofa/jsonboperators-bundle
This command requires you to have Composer installed globally, as explained in the installation chapter of the Composer documentation.
You must add the new functions to be used with DQL into your project's config.yml file, or equivalent if you're using XML, annotations or PHP for config files. If any of the structure is already declared, just append the missing settings.
doctrine:
orm:
dql:
string_functions:
jsonbbykey: fabianofa\JsonbOperatorsBundle\Doctrine\Query\JsonbByKey
jsonbbykeytext: fabianofa\JsonbOperatorsBundle\Doctrine\Query\JsonbByKeyText
jsonbbypath: fabianofa\JsonbOperatorsBundle\Doctrine\Query\JsonbByPath
From now on you can call one of the functions in your query builder definition in methods as select
or andWhere
/where
, such as:
$query = $entityManager->createQueryBuilder("f")
->from("AppBundle:Entity", "e")
->select("jsonbbykeytext(jsoncolumn, 'jsonpropertykey')")
->where("e.id = :id")
->setParameter(":id", 5);
- All functions take two parameters.
- The first parameter is the column name typed as jsonb
- The second parameter can be:
- a single parameter value. Eg:
jsonbbykeytext(jsonbcolumn, 'key')
- a string containing a path of json keys separated by comma (,): Eg:
jsonbbypath(jsonbcolumn, 'key1,key2')
- a single parameter value. Eg:
DQL: ->select("jsonbykey(jsonbcolumn, 'key')
SQL Equivalent: SELECT jsonbcolumn->'key' FROM ...
DQL: ->select("jsonbykey(jsonbcolumn, 'key,key2')
SQL Equivalent: SELECT jsonbcolumn->'key'->'key2' FROM ...
DQL: ->select("jsonbykeytext(jsonbcolumn, 'key')
SQL Equivalent: SELECT jsonbcolumn->>'key' FROM ...
DQL: ->select("jsonbykeytext(jsonbcolumn, 'key,key2')
SQL Equivalent: SELECT jsonbcolumn->>'key'->>'key2' FROM ...
DQL: ->select("jsonbbypath(jsonbcolumn, 'key')
SQL Equivalent: SELECT jsonbcolumn#>>'{key}' FROM ...
DQL: ->select("jsonbykeytext(jsonbcolumn, 'key,key2')
SQL Equivalent: SELECT jsonbcolumn#>>'{key, key2}' FROM ...
There are more operators listed in the official PostgreSQL documentation. The goal is to offer all the operators available. Some native functions may be already be implemented in Doctrine therefore you're encourage to use the native solution instead this package.