0

我使用以下代码使用学说本机查询一些数据:

    $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();

创建的字段是数据库中的 DateTime 字段,目前,它给了我这样的日期:

2012-08-22 14:45:37

我想更改格式,有没有办法告诉教义如何使用结果集映射对其进行格式化?我知道我可以用 php 做到这一点,但我想先看看我是否可以这样做。

4

1 回答 1

2

假设您使用的是 MySQL,您可以在查询中使用DATE_FORMAT() ,如下所示:

DATE_FORMAT(MIN(created), '%d-%m-%Y')) AS oldest

我还建议您为 user_id 使用 $query->setParameter()

$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();

如果您不想在 SQL 中固定格式,您也可以将其设为参数

于 2012-09-11T10:55:13.990 回答