如何按原则分组日期部分

时间:2014-05-29 17:48:55

标签: php mysql symfony doctrine-orm doctrine

我试图按照日期而不是学说中的日期时间对结果进行分组。

以下是我的查询声明:

 GROUP BY CAST(fbaoh.datetimePlaced AS DATE) HAVING sqty > 1 ORDER BY fbaoh.datetimePlaced DESC

这适用于MySQL但不适用于Doctrine,我做错了什么?

这是我得到的错误:

 Error: Cannot group by undefined identification or result variable. (500 Internal Server Error)

谢谢!

以下是我的整个查询:

$query = $em->createQuery("
SELECT fbaoh, fbaoh.id as fbaohid, sum(fbaoh.qty) as sqty, p.id, p.name
FROM WIC\APIBundle\Entity\FBAOrderHistory fbaoh
LEFT JOIN WIC\ListingBundle\Entity\ListingAmazon la
WITH fbaoh.asin = la.standardProductIdValue
LEFT JOIN WIC\ListingBundle\Entity\Listing l
WITH fbaoh.sku = l.product_identifier
LEFT JOIN WIC\ProductBundle\Entity\Product p
WITH l.product = p.id
LEFT JOIN WIC\ListingBundle\Entity\ListingChannel lc
WITH l.listingChannel = lc.id
WHERE fbaoh.webServiceAccountAmazon = lc.webServiceAccount
AND fbaoh.sku = :sku
AND l.id = la.id
AND p.id != ''
GROUP BY CAST(fbaoh.datetimePlaced AS DATE) HAVING sqty > 1 ORDER BY fbaoh.datetimePlaced DESC
");

1 个答案:

答案 0 :(得分:0)

以下是我必须做的事:Big props to this post

我必须创建一个扩展类,以便我可以使用CAST函数。

namespace YOUR\NAME\SPACE;

use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\Lexer;

class CastFunction extends FunctionNode
{
public $firstDateExpression = null;
public $unit = null;    

public function parse(\Doctrine\ORM\Query\Parser $parser)
{
    $parser->match(Lexer::T_IDENTIFIER);
    $parser->match(Lexer::T_OPEN_PARENTHESIS);
    $this->firstDateExpression = $parser->StringPrimary();

    $parser->match(Lexer::T_AS);

    $parser->match(Lexer::T_IDENTIFIER);
    $lexer = $parser->getLexer();
    $this->unit = $lexer->token['value'];

    $parser->match(Lexer::T_CLOSE_PARENTHESIS);
}

public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
{
    return sprintf('CAST(%s AS %s)',  $this->firstDateExpression->dispatch($sqlWalker),    
$this->unit);
    }
}

在config.yml

中注册
 doctrine:
      orm:
           dql:
                string_functions:
                     CAST: Test\MyBundle\DQL\CastFunction

然后在我的查询中使用它:

$query = $em->createQuery("
SELECT fbaoh, CAST(fbaoh.datetimePlaced AS DATE) AS groupDateGrp, fbaoh.id as fbaohid, sum(fbaoh.qty) as sqty, p.id, p.name
FROM WIC\APIBundle\Entity\FBAOrderHistory fbaoh
LEFT JOIN WIC\ListingBundle\Entity\ListingAmazon la
WITH fbaoh.asin = la.standardProductIdValue
LEFT JOIN WIC\ListingBundle\Entity\Listing l
WITH fbaoh.sku = l.product_identifier
LEFT JOIN WIC\ProductBundle\Entity\Product p
WITH l.product = p.id
LEFT JOIN WIC\ListingBundle\Entity\ListingChannel lc
WITH l.listingChannel = lc.id
WHERE fbaoh.webServiceAccountAmazon = lc.webServiceAccount
AND fbaoh.sku = :sku
AND l.id = la.id
AND p.id != ''
GROUP BY groupDateGrp HAVING sqty > 1 ORDER BY fbaoh.datetimePlaced DESC
");