4

我有一个学说查询,它在选择中有一个子查询,以便从另一个表中获取一个字段(并摆脱繁重的左连接)。

问题是 Doctrine 返回给我的别名不是我想要的,因此我很想定制它们。这可能吗?

这是我的查询:

$query->select(
        "id, page_id, status, title, "
      . "segment, url, current_user_id, "
      . "current_user_last_action_time, pt.name,"
    )
        ->addSelect("(SELECT s.username from sfGuardUser s where id = current_user_id) ")
        ->innerJoin( 'PbType pt' )
        ->innerJoin( 'LatestVersion lv WITH version=lv.version' )
        ->where('is_visible = 1')
        ->groupBy( 'page_id' );

这向我返回了这样的查询:

SELECT `p`.`id` AS `p__id`, `p`.`page_id` AS `p__page_id`, 
`p`.`status` AS `p__status`, `p`.`title` AS `p__title`, `p`.`segment` AS `p__segment`,
 `p`.`url` AS `p__url`, `p`.`current_user_id` AS `p__current_user_id`, 
`p`.`current_user_last_action_time` AS `p__current_user_last_action_time`, 
`p2`.`id` AS `p2__id`, `p2`.`name` AS `p2__name`, 
(SELECT `s`.`username` AS `s__username` FROM `sfguard`.`sf_guard_user` `s` WHERE 
`p`.`id` = `p`.`current_user_id`) AS `p__0` 
FROM `personaltable`.`page` `p` INNER JOIN `personaltable`.`type` `p2` ON `p`.`type_id` = `p2`.`id` 
INNER JOIN `personaltable`.`latest_page_version` `p3` ON `p`.`page_id` = `p3`.`page_id` 
AND `p`.`version` = `p3`.`version` WHERE `p`.`is_visible` = 1 
GROUP BY `p`.`page_id`

就是p__0我想要改变的。有没有办法做到这一点?

4

2 回答 2

0

它应该像

->addSelect("(SELECT s.username from sfGuardUser s where id = current_user_id) AS alias")
于 2012-12-12T11:40:52.940 回答
0

前段时间我遇到了同样的问题,刚刚找到了一个可行的解决方案,但不使用 orm。通过像这样通过您当前的学说连接使用真正的 mysql 来尝试它。

$query = 'SELECT p.id, p.page_id, p.status, p.title, p.segment, p.url, p.current_user_id,
                 p.current_user_last_action_time, p2.name, 
         ( SELECT s.username from sfGuardUser s where id = p.current_user_id ) as XXX
         FROM personaltable.page p 
         INNER JOIN personaltable.type p2 ON p.type_id = p2.id 
         INNER JOIN personaltable.latest_page_version p3 ON p.page_id = p3.page_id AND p.version = p3.version 
         WHERE p.is_visible = 1 
         GROUP BY p.page_id';


$connection = Doctrine_Manager::getInstance()->getCurrentConnection();
$statement = $connection->execute($query)->fetchAll();

foreach ($statement as $key => $val) {
    $id = $statement[$key]['XXX'];
}

XXX 是您不想自定义的别名。

我知道这不是好的风格,但我无法以任何其他方式做到这一点。

于 2012-12-13T13:37:24.147 回答