2017-04-12 67 views
0

我是新教義,並想用它學說2個多重選擇元素,別名DATE_FORMAT

SELECT DATE_FORMAT(DATE(created_at), '%m-%Y') AS 'date', 
     COUNT(DISTINCT(id)) AS 'value' 
FROM users 
GROUP BY YEAR(DATE(created_at)), MONTH(DATE(created_at)) 

,使我的數據庫查詢我看了一些文檔,但仍然有一些問題

如何我選擇了多個元素;給我選定的元素提供別名,做一個左連接。 WEEK()MONTH()和YEAR()函數是否可用? DATE_FORMAT(來自mysql)是否可用?

謝謝

回答

1

我相信你應該使用查詢構建器(http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/query-builder.html)。

考慮日期,你可以使用symfony datetime對象並對它們進行格式化。 左加入leftJoin方法可用於(http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/query-builder.html

<?php 
// $qb instanceof QueryBuilder 

$qb->select('u as aliasName')  //see for alias 
    ->from('User', 'u') 
    ->leftJoin('u', 'phonenumbers', 'p', 'u.id = p.user_id') //see  for left join 
    ->where('u.id = ?1') 
    ->addwhere(u.date < :date) 
    ->orderBy('u.name', 'ASC') 
    ->setParameter('date', $symfonyDateTime->format('Y-m-d')); //see for date 

相反的QueryBuilder的,你也可以嘗試DQL(http://symfony.com/doc/current/doctrine.htmlhttp://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html):

$em = $this->getDoctrine()->getManager(); 
$query = $em->createQuery(
    'SELECT p 
    FROM AppBundle:Product p 
    WHERE p.price > :price 
    ORDER BY p.price ASC' 
) 
->setParameter('price', 19.99); 

$products = $query->getResult(); 
1

你可以安裝doctrine extensions才能使用功能如:

DATE, MINUTE, HOUR, DAY, WEEK等等。

例子:

學說配置

doctrine: 
    dbal: 
     .... 
     orm: 
     auto_generate_proxy_classes: "%kernel.debug%" 
     entity_managers: 
      default: 
       dql: 
        datetime_functions: 
        DATE_FORMAT: DoctrineExtensions\Query\Mysql\DATE_FORMAT 

然後你就可以很容易的添加這樣的別名:

DATE_FORMAT(s.createdAt,'%Y-%m-01') as date