When using Kohana DB, how do I avoid code duplication when counting is necessary for pagination?

Using the Kohana query builder, is it possible to build my query in parts.

Then do the counting on the specified query.

Then run the query itself.

All without the need to write repeating conditional expressions ... one for counting and one for results ...

Adding

DB::select(array('COUNT("pid")', 'mycount'))

Only one entry is displayed in the main query.

Is it possible to execute an account and somehow delete

array('COUNT("pid")', 'mycount')

from the selection ...

Right now, the only way I can think of is to find and replace on the SQL code itself, and then just run the specified SQL code ... there should be a better way, though ... I hope ...

Thank!

+1
source share
2

3 . , - . -, , # 1 # 2. JOINs WHERE - , # 3. , .

/* 1 */
public function get_stuff($pagination = false){
    $query = DB::select(/* ... columns here ... */);
    $query = $this->get_stuff_query($query);
    if($pagination) $query->limit($pagination->items_per_page)->offset($pagination->offset);
    return $query->execute();
}

/* 2 */
public function get_stuff_count(){
    $query = DB::select(array('COUNT("id")', 'total_rows'));
    $query = $this->get_stuff_query($query);
    $result = $query->execute();
    return $result->get('total_rows',0);
}

/* 3 */
private function get_stuff_query($query){
    $query->from(/* tablename */);
    $query->join(/* ... */);
    $query->where(/* ... */);
    return $query;
}
+2

count_last_query()

// $db is a Database instance object
$count = $db->count_last_query();
+2

All Articles