#
#
# artur #2014-09-26 12:27:18
Kohana
# artur #, 2014-09-26 12:27:18

Kohana 3.3 and Query Builder - how to select and recalculate rows in one query through the model?

Hello.
Everything is pretty trite, but nevertheless I can’t figure out how to make SELECT and COUNT according to different criteria in one query through the model.
Here is a simple example as already tried:
(select all users whose status = 1)

$query = DB::select('id', 'name', 'status')
->from('users')
->where('status', '=', 1);

I add a couple of lines to it to count ALL users, regardless of status:
$total = clone $query;
$total ->select(array(DB::expr('COUNT(id)'), 'total_users'))->from('users')->execute()->as_array();

As a result, I test and get an array with the last user and the number of all total_users, this is not quite what I need.
I need to get the full array of users by criterion and the total number without any criterion, but I need to do this through the model in one request. I know how to work with the model, I would like to get help with the request.
At the moment I am recalculating the total number of users with a separate query:
$total = DB::select(array(DB::expr('COUNT(`id`)'), 'total_users'))->from('users')->execute()->get('total_users');

, but this creates an extra load on the database, and the amount of data that will need to be recalculated on each page is quite large.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shamanov, 2014-09-26
@passshift

JOIN or UNION, but the second query must either add the field to all records of the first one, or have the same list of fields. but it's not at all clear why such perversions - if you are afraid of an extra load, then just cache the results.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question