简体   繁体   中英

How make doctrine findby to json field without native query

I use json column in doctrine 2 (In MySQL database). Actually, I made my search in json with native query like

$rsm = new ResultSetMappingBuilder($entityManager);
$rsm->addRootEntityFromClassMetadata(\blabla\MyObject::class, 'o');
$query = $entityManager->createNativeQuery('select o.* from my_objects o where json_extract(jsonData, "$.test.key1")= "value1"', $rsm); 
//jsonData column contains {"test": {"key1" : "value1"}}
$result = $query->getResult();

Is it possible the made query like that without the native query mechanism ? (like a findBy)

Thanks in advance for your help ;)

I solved my problem using DQL extension scienta/doctrine-json-functions

Install it

composer req scienta/doctrine-json-functions

Usage

$queryBuilder = $entityManager->createQueryBuilder();
$query = $queryBuilder
    ->select("o")
    ->from(\bla\bla\MyObject::class, "o")
    ->where("JSON_EXTRACT(o.jsonData, :jsonPath) = :value ")
    ->setParameter('jsonPath', '$.test.key1')
    ->setParameter('value', 'value1')
    ->getQuery();

$co = $query->getResult();

I was just facing the same problem, but didn't want to install an additional extension. The code snippet from the original question just needs a small enhancement to work:

$rsm = $this->createResultSetMappingBuilder('n');
$rsm->addRootEntityFromClassMetadata(MyObject::class, 'n');
$rawQuery = sprintf('SELECT %s FROM my_objects n WHERE JSON_EXTRACT(current_state, \'$.processing\')', $rsm->generateSelectClause());
$query = $this->_em->createNativeQuery($rawQuery, $rsm);
return $query->getResult();

And it works like a charm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM