0

I'm trying to get some some results from a leaderboard to be served in a JSON format.

My actual query, which is working is as follows:

...
$pos = 25 //some position
$cnx->beginTransaction();
        $cnx->executeQuery('SET @rownum := 0');
        $sql = "
        SELECT * FROM (
            SELECT @rownum := @rownum + 1 AS rank, id, name, birthdate, gamesplayed,country,city
            FROM board  ORDER BY score DESC
        ) as result 
        WHERE result.rank >= (" . $pos . "-10)  and result.rank <= (" . $pos . "+10)
        ORDER BY rank
        ";

$preresults = $cnx->executeQuery($sql);
$cnx->commit();

$results = $preresults->fetchAll();

The request works, but I lost all fields types (cast), all values are in string format.

How to get values in proper type like if I use dql (objects)?

1 Answer 1

1

you need to use the ResultSetMappingBuilder class like this:

$rsm = new ResultSetMappingBuilder($this->entityManager);
$rsm->addRootEntityFromClassMetadata('App:YourEntity', 'y');
$sql = "SELECT * FROM (
        SELECT @rownum := @rownum + 1 AS rank, id, name, birthdate, gamesplayed,country,city
        FROM board  ORDER BY score DESC
    ) as result 
    WHERE result.rank >= (" . $pos . "-10)  and result.rank <= (" . $pos . "+10)
    ORDER BY rank";
$query = $this->entityManager->createNativeQuery($sql, $rsm);

return $query->getResult();

That will return an array of YourEntity[]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.