I'm Natively querying for some data using doctrine using the code below:
$sql = "SELECT count(type) AS notifications,
count(DISTINCT subject) AS users,
count(DISTINCT object_activity) AS activities,
count(DISTINCT object_activity_relationship) AS relationships,
type,
min(created) as oldest,
max(created) as latest "
."FROM notification n "
."WHERE target_user='".$user->id."' AND notification_read=0 "
."GROUP BY type "
."ORDER BY latest ";
$rsm = new \Doctrine\ORM\Query\ResultSetMapping;
$rsm->addScalarResult('type', 'type');
$rsm->addScalarResult('oldest', 'oldest');
$rsm->addScalarResult('latest', 'latest');
$rsm->addScalarResult('users', 'users');
$rsm->addScalarResult('notifications', 'notifications');
$rsm->addScalarResult('activities', 'activities');
$rsm->addScalarResult('relationships', 'relationships');
$query = $this->_em->createNativeQuery($sql, $rsm);
return $query->getResult();
The created field is a DateTime field in the database, and currently, it's giving me dates like this:
2012-08-22 14:45:37
I want to change the format, is there a way to tell doctrine how to format it using the resultsetmapping? I know I can do it with php, but I want to see if I can do it this way first.
Assuming you are using MySQL you could use DATE_FORMAT() in your query like so:
DATE_FORMAT(MIN(created), '%d-%m-%Y')) AS oldest
I'd also recommend using the $query->setParameter() for your user_id
$sql = "SELECT
COUNT(type) AS notifications,
COUNT(DISTINCT subject) AS users,
COUNT(DISTINCT object_activity) AS activities,
COUNT(DISTINCT object_activity_relationship) AS relationships,
type,
DATE_FORMAT(MIN(created), '%d-%m-%Y') AS oldest,
DATE_FORMAT(MAX(created), '%d-%m-%Y') AS latest
FROM
notification n
WHERE
target_user = ':user_id'
AND
notification_read = 0
GROUP BY
type
ORDER BY
latest";
$rsm = new \Doctrine\ORM\Query\ResultSetMapping;
$rsm->addScalarResult('type', 'type');
$rsm->addScalarResult('oldest', 'oldest');
$rsm->addScalarResult('latest', 'latest');
$rsm->addScalarResult('users', 'users');
$rsm->addScalarResult('notifications', 'notifications');
$rsm->addScalarResult('activities', 'activities');
$rsm->addScalarResult('relationships', 'relationships');
$query = $this->_em->createNativeQuery($sql, $rsm);
$query->setParameter('user_id', $user->id);
return $query->getResult();
If you don't want the format fixed in the SQL you can also make it a parameter