protected function &_queryExport($query)
{
$data = $query->export($this);
if (!$query->limit() || !($model = $query->model())) {
return $data;
}
foreach ($query->relationships() as $relation) {
if ($relation['type'] !== 'hasMany') {
continue;
}
$pk = $this->name($model::meta('name') . '.' . $model::key());
if ($query->order()) {
list($fields, $orders) = $this->_distinctExport($query);
array_unshift($fields, "DISTINCT ON({$pk}) {$pk} AS _ID_");
$command = $this->renderCommand('read', array('limit' => null, 'order' => null, 'fields' => implode(', ', $fields)) + $data);
$command = rtrim($command, ';');
$command = $this->renderCommand('read', array('source' => "( {$command} ) AS _TEMP_", 'fields' => '_ID_', 'order' => "ORDER BY " . implode(', ', $orders), 'limit' => $data['limit']));
} else {
$command = $this->renderCommand('read', array('fields' => "DISTINCT({$pk}) AS _ID_") + $data);
}
$result = $this->_execute($command);
$ids = array();
foreach ($result as $row) {
$ids[] = $row[0];
}
if (!$ids) {
$data = null;
break;
}
$conditions = array();
$relations = array_keys($query->relationships());
$pattern = '/^(' . implode('|', $relations) . ')\\./';
foreach ($query->conditions() as $key => $value) {
if (preg_match($pattern, $key)) {
$conditions[$key] = $value;
}
}
$data['conditions'] = $this->conditions(array($pk => $ids) + $conditions, $query);
$data['limit'] = '';
break;
}
return $data;
}