Request on key/value in a JSON type field with Doctrine2

耗尽温柔 提交于 2021-02-08 13:18:18

问题


I'm trying to figure out how, in a symfony 3.4 app, to retrieve (through a repository method, with a DQL request for example) entities depending on a value for a specific key in a "json" typed column. Saw there's some stuff possible with postgre but I didnt find anything with mariaDB

Let's say I get an entity Letter

with this property :

/**
 *
 * @ORM\Column(type="json")
 */
private $metadatas;

which contains, for example:

 {
    "key1": "value",
    "key2": "value"
 }

How can I, or, Is it possible to request my DB to get letters with a specific value for a specific key in metadatas column.

Something like that :

public function getByKeyValue($key, $value)
      {
          $em = $this->_em;
          $dql = "SELECT l FROM AppBundle:Letter l
                  WHERE l.metadatas->:key = :value
                  ";

          $query = $em->createQuery($dql);
          $query->setParameter('key', $key);
          $query->setParameter('value', $value);


          return $query->getResult();
      } 

some infos :

php7.1, mariadb 10.2+, doctrine/dbal ^2.6, doctrine orm ^2.5

Thanks a lot.


回答1:


You can use ScientaNL/DoctrineJsonFunctions

Install it through composer by adding:

"scienta/doctrine-json-functions": "~4.0",

Register the json function that is needed in the doctrine configuration, in this case JSON_CONTAINS:

doctrine:
    orm:
        entity_managers:
            some_em: # usually also "default"
                dql:
                    string_functions:
                        JSON_CONTAINS: Scienta\DoctrineJsonFunctions\Query\AST\Functions\Mysql\JsonContains

In my case, I just added:

doctrine:
    orm:
         dql:
              string_functions:
                  JSON_CONTAINS: Scienta\DoctrineJsonFunctions\Query\AST\Functions\Mysql\JsonContains

Use it:

$queryBuilder = $this->getDoctrine()->getRepository('AppBundle:Letter')->createQueryBuilder('lt');
$queryBuilder
        ->where("JSON_CONTAINS(lt.metadatas, :mvalue, '$.key') = 1");

$queryBuilder->setParameter('mvalue', '"value"');
$query = $queryBuilder->getQuery();
return $query->getResult();

In dql, it should be something like:

$dql = "SELECT l FROM AppBundle:Letter l
              WHERE JSON_CONTAINS(lt.metadatas, :mvalue, '$.key') = 1
              ";

Note $.key is the json key to filter and mvalue should be included in its json encoded format, in this case with double quotes.

References:

MySql json-search-functions



来源:https://stackoverflow.com/questions/49279909/request-on-key-value-in-a-json-type-field-with-doctrine2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!