2016-05-13 18 views
0

我知道這個問題已經成了老生常談,但沒有就如何解決這個使用原則回答:尋找之和分組從數據庫中獲取的數據一個月明智

所以這裏是我的學說查詢取時間戳和量表:

$q = $repo->createQueryBuilder('s') 
      ->select('s.timestamp','s.amt') 
      ->where('s.disId=:id') 
      ->setParameter('id', $cid) 
      ->getQuery() 
      ->getArrayResult(); 

目前我獲取所有個人從表中的行,我所要的輸出智者總結AMT(量)月和記錄相應的顯示。

感謝您的幫助

回答

1

如果您的日期存儲爲時間戳,那麼它是不可能直接做,因爲學說ORM目前不支持的功能,如MySQL的MONTH(),您需要在組使用條款。 可能的解決方案:

  1. 安裝包,增加了這些功能,例如 https://github.com/beberlei/DoctrineExtensions和使用functitons MONTH()和FROM_UNIXTIME()從那裏

  2. 使用原則的原生查詢: http://doctrine-orm.readthedocs.io/projects/doctrine-orm/en/latest/reference/native-sql.html

  3. 使用學說的DBAL層: http://doctrine-orm.readthedocs.io/projects/doctrine-dbal/en/latest/

爲您簡單的將是可能選項3,代碼可能是這樣的:

$em = $this->get("doctrine")->getManager(); 
$conn = $em->getConnection(); 
$sql = "SELECT MONTH(FROM_UNIXTIME(s.timestamp)) as mon, SUM(s.amt) as total FROM tablename s WHERE s.dis_id = ? GROUP BY MONTH(FROM_UNIXTIME(s.timestamp)) ORDER BY 1"; 
$stmt = $conn->prepare($sql); 
$stmt->bindValue(1, $cid); 
$stmt->execute(); 
$all_rows = $stmt->fetchAll(); 
foreach ($all_rows as $row) { 
    echo "Month: {$row["mon"]}, Total: {$row["total"]} \n"; 
} 
+0

個人更喜歡選項1,感謝您發佈多個解決方案! – kero

+0

它返回一個空數組!輸出結果是:[] –

+0

我是否在安裝軟件包時出錯? –

0

試試這個:

$q = $repo->createQueryBuilder('s') 
     ->select('s.timestamp','sum(s.amt)') 
     ->where('s.disId=:id') 
     ->groupBy('s.month')//your month field name of database 
     ->setParameter('id', $cid) 
     ->getQuery() 
     ->getArrayResult(); 

使用GROUPBY你會得到結果。

相關問題