代码之家  ›  专栏  ›  技术社区  ›  mattalxndr

按条令1.2中的生成字段排序

  •  0
  • mattalxndr  · 技术社区  · 15 年前

    我正在使用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();
    

    以下是我得到的错误:

    致命错误:未捕获的异常'distric_query_exception'(消息'unknown column title'在/[删除]/lib/distric/distric/query/orderby.php:94堆栈跟踪:0/[删除]/lib/distric/query/abstract.php(2077):distric_query_orderby->parse('a.title')1/[删除]/lib/distric/distric/query.php(1160):distric_query_abstract->_processdqlquerypart('orderby',array)2/[removed]/lib/distric/distric/query.php(1126):distric诳query->buildsqlquery(false)诳3/[removed]/lib/distric/query/abstract.php(1137):distric诳query->getsqlquery(array,false)诳4/[removed]/lib/distric/distric/query/abstract.php(1106):distric组件(数组)5/[已删除]/lib/distric/distric/query/abstract.php(1001):distric query abstract->prequery(array)6/srv/web/museumfounda in/[已删除]/lib/distric/query/orderby.php,第94行

    1 回复  |  直到 15 年前
        1
  •  1
  •   DrColossos    15 年前

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

    ->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 所以代码很容易维护。