【问题标题】:Ordering by a generated field in Doctrine 1.2在 Doctrine 1.2 中按生成的字段排序
【发布时间】:2011-04-08 01:14:47
【问题描述】:

我正在使用 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 /[REMOVED]/lib/doctrine/Doctrine/Query.php(1126): Doctrine_Query->buildSqlQuery(false) #3 /[REMOVED]/lib/doctrine/Doctrine/Query/Abstract.php( 1137): Doctrine_Query->getSqlQuery(Array, false) #4 /[删除]/lib/doctrine/Doctrine/Query/Abstract.php(1106): Doctrine_Query_Abstract->_getDqlCallbackComponents(Array) #5 /[删除]/lib/学说/Doctrine/Query/Abstract.php(1001): Doctrine_Query_Abstract->_preQuery(Array) #6 /srv/web/museumfounda in /[REMOVED]/lib/doctrine/Doctrine/Query/Orderby.php on line 94

【问题讨论】:

    标签: php doctrine doctrine-query


    【解决方案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 的值,以便代码易于维护。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-19
      相关资源
      最近更新 更多