在Doctrine select语句中使用'case when'

时间:2009-10-14 08:45:25

标签: php sql doctrine

我有一个我想用Doctrine执行的选择查询:

 $resultset = Doctrine_Query::create()
    ->select("t.code, t.description, case when t.id_outcome = 1 then 1 else 0 end as in_progress")
    ->from('LuOutcome t')
    ->orderBy('t.rank')
    ->fetchArray();

它就是'案件'上的barfs。文档没有提到它是否可能。

我想知道Doctrine是否缺乏这样做的能力。如果是这样,这是一个相当重大的遗漏。有没有人知道解决方法?

6 个答案:

答案 0 :(得分:25)

我遇到了同样的问题,乍一看似乎有一个解决方法。我相信你可以“愚弄”Doctrine Select解析器,将它作为一个子查询处理,方法是将它包装在括号中。

尝试一下:

$resultset = Doctrine_Query::create()
->select("t.code, t.description, (case when t.id_outcome = 1 then 1 else 0 end) as in_progress")
->from('LuOutcome t')
->orderBy('t.rank')
->fetchArray();

答案 1 :(得分:3)

BNF grammar for the Doctrine Query Language似乎不包含与CASE构造相关的任何内容。

答案 2 :(得分:3)

答案 3 :(得分:0)

我在这里遇到了同样的问题。我的项目非常陈旧,并试图快速修复它。所以我只需更改Doctrine的代码,以便我可以使用“case when”。这是我的Doctrine 1.1.3代码。

Doctrine / Query.php,将行从658更改为674:

        if (count($terms) > 1 || $pos !== false) {
            if($terms[0]=='case')
            {
                $terms=explode(" as ", $reference);
                $expression = array_shift($terms);
                $alias = array_pop($terms);

                if ( ! $alias) {
                    $alias = substr($expression, 0, $pos);
                }

                $componentAlias = $this->getExpressionOwner($expression);

                $tableAlias = $this->getTableAlias($componentAlias);

                $expression=str_replace($componentAlias, $tableAlias, $expression);

                $index=0;

                $sqlAlias = $tableAlias . '__' . $alias;
            }
            else
            {
                $expression = array_shift($terms);
                $alias = array_pop($terms);

                if ( ! $alias) {
                    $alias = substr($expression, 0, $pos);
                }

                $componentAlias = $this->getExpressionOwner($expression);
                $expression = $this->parseClause($expression);

                $tableAlias = $this->getTableAlias($componentAlias);

                $index    = count($this->_aggregateAliasMap);

                $sqlAlias = $this->_conn->quoteIdentifier($tableAlias . '__' . $index);
            }

            $this->_sqlParts['select'][] = $expression . ' AS ' . $sqlAlias;

这不是一个很大的改变,但它帮助了我......

答案 4 :(得分:0)

adavea所述,Doctrine现在增加了对CASE表达式的支持。您可以做类似

的操作
 $resultset = Doctrine_Query::create()
->select("t.code, t.description")
->addSelect("CASE WHEN(t.id_outcome = 1) THEN 1 ELSE 0 END as in_progress")
->from('LuOutcome t')
->orderBy('t.rank')
->fetchArray();

希望这可以帮助某人,谢谢!

答案 5 :(得分:-3)

我建议您不要使用此CASE语法来解决此问题。看起来很棘手。

你为什么不想

$resultset = Doctrine_Query::create()
    ->select("t.code, t.description, t.id_outcome")
    ->from('LuOutcome t')
    ->orderBy('t.rank')
    ->fetchArray();

然后循环遍历$ resultset并根据(id_outcome)值手动创建此字段(in_progress)。你可以使用一些简单的小方法。

优点:

  • 简单
  • 可读