2

在 Zend Framework 2 中将 $select->order(...) 添加到先前组合的 Select 时,“order by”将仅添加到第一个 Select 语句中。

SELECT `user`.* 
FROM `user` WHERE `user_id` = :where1 
ORDER BY `starttime_dt` ASC ) 
UNION 
( SELECT `user`.* 
FROM `user` 
WHERE `user_id` != :subselect1where1 )

我需要的是排序将应用于完整的选择。这里已经描述了一个解决方案

https://github.com/zendframework/zf2/issues/5162#issuecomment-36294281

但此解决方案适用于 SQL 适配器。

如何使用 Table Gateway 做到这一点?

我的代码目前看起来像这样(导致上面的语句)

$select = $this->tableGateway->getSql()->select();
$select2 = clone $select;
$select->where->equalTo('user_id', $user_id);
$select2->where->notEqualTo('user_id', $user_id);
$select->combine($select2);
$select->order('starttime_dt');
$resultSet = $this->tableGateway->selectWith($select);
4

1 回答 1

2

You would do it with table gateway the same way it was illustrated in the link you provided.

Your code would look like

$select = $this->tableGateway->getSql()->select();
$select2 = clone $select;
$select->where->equalTo('user_id', $user_id);
$select2->where->notEqualTo('user_id', $user_id);
$select->combine($select2);

$combinedSelect = (new Zend\Db\Sql\Select)->from(['sub' => $select])->order('starttime_dt');

$statement = $this->sql->prepareStatementForSqlObject($combinedSelect);
$result = $statement->execute();
$resultSet = clone $this->resultSetPrototype;
$resultSet->initialize($result);

You wouldn't be able to use the TableGateway's selectWith method because it's going to check that the provided Select's table matches the TableGateway's table.

于 2015-04-15T17:53:19.400 回答