phpcodeignitercodeigniter-4

How to get the filtered record count for a query?


I am using codeigniter 4 model for a an application which I work. I would like to get the filtered record count for a query as shown.

My code is a shown below:

$model = new LocationModel();
$builder = $model->builder();

if($filterName != "" && $filterValue != "") {
$builder->where($filterName, $filterValue);
}

$data = [];
$data['locations'] = $model->findAll();
$data['recordCount'] = $model->countAllResults();

I tried countAllResults as shown in my code above and it gives the count of full records available in table.

Can you please suggest a way to get the count fetched in the findAll?

Please note that I want the results fetched in the above query(not the record count in the database table).


Solution

  • You cant mix the Model's method findAll() after manual builder conditions. If you're using the builder, then use $builder->get()

    # to get filtered count without resetting the query
    $data['recordCount'] = $builder->countAllResults(false); # resets query. Default true
    
    # to get filtered results
    $data['locations'] = $builder->get()->getResultArray();