Skip to content

fix fetchPairs() to work with referenced tables #44

Closed
wants to merge 1 commit into from

2 participants

@xpavp03
xpavp03 commented Apr 16, 2012

Take this query as an example:
$notorm->course[92]->hole('deleted', null)->order('rank')->fetchPairs('rank', 'rank');

It generates the following SQL:
SELECT holes.course, rank, rank
FROM holes
WHERE (holes.course IN (92)) AND (deleted IS NULL)
ORDER BY holes.course, rank

The query itself is all right but fetchPairs() in your implementation returned
array('92' => '18')
instead of
array('1'=>'1', '2'=>'2', ..., '18' => '18');

The culprit was that fetchPairs used $values[0] as key which in this case was the course id. And I couldn't remove course id from the first position in results.

I suggest to make fetchPairs() use $key/$value directly (instead of numerical indexes).

@xpavp03
xpavp03 commented Apr 27, 2013

I see it's more complicated in cases where key or value references a field in another table. Here's an updated patch:

-           $values = array_values(iterator_to_array($row));
-           $return[$values[0]] = ($value != "" ? $values[(isset($values[1]) ? 1 : 0)] : $row); // isset($values[1]) - fetchPairs("id", "id")
+           $values = iterator_to_array($row);
+           list($key) = array_slice(preg_split('/\W+/', $key), -1, 1);  // parent:table.key => key
+           if ($value) {
+             list($value) = array_slice(preg_split('/\W+/', $value), -1, 1);
+           }
+           $return[ $values[$key] ] = ($value != "" ? $values[$value] : $row);
@vrana
Owner
vrana commented Jun 27, 2013

The problem with this approach is that literal value of $key may not be present in the result. For example if $key = "test" then result contains test (without backticks).

@vrana
Owner
vrana commented Jun 27, 2013

Markdown screwed the formatting but I hope it's obvious.

@vrana vrana closed this Jun 27, 2013
@vrana
Owner
vrana commented Jun 27, 2013

I've fixed it by other means.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.