0

我正在使用 preDqlSelect() 回调来添加“虚拟字段”。但是我的查询验证必须在回调被触发之前发生,因为当我查询该模型时,我无法按该新字段排序。

这是我的回调:

class Artist extends BaseArtist
{
    public function preDqlSelect(Doctrine_Event $event)
    {

        // Add title field (concatenation of first_name, last_name, and company fields)
        $params = $event->getParams();
        $q = $event->getQuery();
        $a = $params['alias'];
        if (
        $q->contains($a.'.first_name')
        && $q->contains($a.'.last_name')
        && $q->contains($a.'.company')
        ) {
            $exists = '!ISNULL(NULLIF('.$a.'.%s, \'\'))';
            $value = 'IFNULL('.$a.'.%1$s, \'\')';
            $if = sprintf($exists, 'first_name').' OR '.sprintf($exists, 'last_name');
            $thenPiece1 = sprintf($value, 'first_name').', \' \', '.sprintf($value, 'last_name');
            $thenPiece2 = 'IF('.sprintf($exists, 'company').', CONCAT(\' (\', '.sprintf($value, 'company').', \')\'), \'\')';
            $then = 'TRIM(CONCAT('.$thenPiece1.', '.$thenPiece2 .'))';
            $else = sprintf($value, 'company');
            $select = 'IF('.$if.', '.$then.', '.$else.') AS title';
            $q->addSelect($select);
        }
    }
// ...

这是我的查询:

$artists = Doctrine_Query::create()
    ->select('a.id, a.first_name, a.last_name, a.company')
    ->from('Artist a')
    ->innerJoin('a.Products p')
    ->where('a.active <> 0')
    ->andWhere('p.active <> 0')
    ->orderBy('a.title')
    ->execute();

这是我得到的错误:

致命错误:在 /[REMOVED]/lib/doctrine/Doctrine/Query/Orderby.php:94 中未捕获的异常 'Doctrine_Query_Exception' 带有消息 'Unknown column title' 堆栈跟踪:#0 /[REMOVED]/lib/doctrine/Doctrine/ Query/Abstract.php(2077): Doctrine_Query_Orderby->parse('a.title') #1 /[删除]/lib/doctrine/Doctrine/Query.php(1160): Doctrine_Query_Abstract->_processDqlQueryPart('orderby', Array ) #2 /[删除]/lib/doctrine/Doctrine/Query.php(1126): Doctrine_Query->buildSqlQuery(false) #3 /[删除]/lib/doctrine/Doctrine/Query/Abstract.php(1137): Doctrine_Query->getSqlQuery(Array, false) #4 /[REMOVED]/lib/doctrine/Doctrine/Query/Abstract.php(1106): Doctrine_Query_Abstract->_getDqlCallbackComponents(Array) #5 /[REMOVED]/lib/doctrine/Doctrine /Query/Abstract.php(1001): Doctrine_Query_Abstract->_preQuery(Array) #6 /srv/web/museumfounda in /[REMOVED]/lib/doctrine/Doctrine/Query/Orderby.php 第 94 行

4

1 回答 1

1

与此类似的东西应该可以工作:

->select('a.id, a.first_name, a.last_name, a.company, IF(your constructed query from above) AS title')

这应该允许您像现在一样使用您的订购条款。为了使它更好,您可以在一个Table类中创建查询并从中传递值,your constructed query from above以便代码易于维护。

于 2010-09-04T17:51:27.020 回答