Row Index Finder (rowindex)
To enable these methods, add 'rowindex' to DataMapper's config, under 'extensions'.
This extension allows you to determine on which row a specific item is found across a non-LIMITed query.
This can be very useful for switching to the correct page of a long list of results after adding or editing a new item.
row_index($id, $leave_select, $distinct_on)
- $id: Either a DataMapper object, or the ID of one, to look up.
- $leave_select: (Optional) If provided, make sure these items are not removed from the SELECT part of the query..
- $distinct_on: (Optional) If TRUE, use DISTINCT ON when running the query. See below.
- Returns: The index of the item, or FALSE if the item was not found..
The $leave_select and $distinct_on arguments are used to assist in complex queries.
- If you know that certain selected columns must be selected in order for the query to run, list them here.
- If your database supports it, using DISTINCT ON() ensures that you get a distinct set of results, even over multiple columns.
This method will clone your object, so you can use the existing query to load the content.
Usage
$widgets = new Widget(); // user sorting $widgets->order_by($this->session->userdata('widget_sort_column'), $this->session->userdata('widget_sort_dir')); $edited_item = $this->session->userdata('last_edited_widget'); // which row? $widgets->load_extension('rowindex'); $index = $widgets->row_index($edited_item); // now load that page (you could redirect instead) $widgets->get_paged($index, $this->session->userdata('widget_page_size'), TRUE);
row_indices($ids, $leave_select, $distinct_on)
- $ids: Either a DataMapper object, the ID of one, to look up, or an array of either.
- $leave_select: (Optional) If provided, make sure these items are not removed from the SELECT part of the query..
- $distinct_on: (Optional) If TRUE, use DISTINCT ON when running the query. See below.
- Returns: An array of row => id that contained one of the $ids.
A simple variation of the above, but this can be used to find multiple IDs in one pass.
The results are an array are associative. The key is the row number, and the value is the row's ID. This allows for non-distinct queries.
Example
$widgets = new Widget(); $widgets->load_extension('rowindex'); $indices = $widgets->row_indices(array(1, 3, 22)); print_r($indices); // echos something like: array( // row -- ID 5 => 3, 14 => 1, 16 => 22 )
How it Works
This extension uses some fairly complex methods to try and generate the simplest query needed to get the index of every item in proper order. It does this by eliminating all unnecessary SELECTS.
Then the result set is looped over, and the ID or IDS are looked for. If any are found, they are returned.
It's not super efficient, but there aren't any cross-DB patterns that I know of to do this.