public function findMulti($types, $sql, $bindings = array(), $remappings = array(), $queryTemplate = ' %s.%s AS %s__%s')
{
if (!is_array($types)) {
$types = explode(',', $types);
}
if (!is_array($sql)) {
$writer = $this->toolbox->getWriter();
$adapter = $this->toolbox->getDatabaseAdapter();
//Repair the query, replace book.* with book.id AS book_id etc..
foreach ($types as $type) {
$pattern = " {$type}.*";
if (strpos($sql, $pattern) !== FALSE) {
$newSelectorArray = array();
$columns = $writer->getColumns($type);
foreach ($columns as $column => $definition) {
$newSelectorArray[] = sprintf($queryTemplate, $type, $column, $type, $column);
}
$newSelector = implode(',', $newSelectorArray);
$sql = str_replace($pattern, $newSelector, $sql);
}
}
$rows = $adapter->get($sql, $bindings);
} else {
$rows = $sql;
}
//Gather the bean data from the query results using the prefix
$wannaBeans = array();
foreach ($types as $type) {
$wannaBeans[$type] = array();
$prefix = "{$type}__";
foreach ($rows as $rowkey => $row) {
$wannaBean = array();
foreach ($row as $cell => $value) {
if (strpos($cell, $prefix) === 0) {
$property = substr($cell, strlen($prefix));
unset($rows[$rowkey][$cell]);
$wannaBean[$property] = $value;
}
}
if (!isset($wannaBean['id'])) {
continue;
}
if (is_null($wannaBean['id'])) {
continue;
}
$wannaBeans[$type][$wannaBean['id']] = $wannaBean;
}
}
//Turn the rows into beans
$beans = array();
foreach ($wannaBeans as $type => $wannabees) {
$beans[$type] = $this->redbean->convertToBeans($type, $wannabees);
}
//Apply additional re-mappings
foreach ($remappings as $remapping) {
$a = $remapping['a'];
$b = $remapping['b'];
$matcher = $remapping['matcher'];
$do = $remapping['do'];
foreach ($beans[$a] as $bean) {
foreach ($beans[$b] as $putBean) {
if ($matcher($bean, $putBean, $beans)) {
$do($bean, $putBean, $beans, $remapping);
}
}
}
}
return $beans;
}