Welcome Guest, Not a member yet? Register   Sign In
Count model result
#1

how can i count  rows of model result ? 
For example :
Code:
$usersModel = new UsersModel();
$users = $usersModel->findAll();
//count all users
?
Reply
#2

(This post was last modified: 02-10-2022, 07:27 AM by demyr.)

Hi,

Code:
public function number_of_x_item($x_id){
$db      = \Config\Database::connect();
$builder = $db->table('your_db_table as dbt');
$query = $builder->select('*')
->where('dbt.item_id', $x_id);

return $query->countAllResults();
}
Reply
#3

(02-10-2022, 07:26 AM)demyr Wrote: Hi,

Code:
public function number_of_x_item($x_id){
$db      = \Config\Database::connect();
$builder = $db->table('your_db_table as dbt');
$query = $builder->select('*')
->where('dbt.item_id', $x_id);

return $query->countAllResults();
}

with model is not possible ?
Reply
#4

Yeah, it was for model. You can also check on Documentation page
Reply
#5

(02-10-2022, 06:26 AM)pippuccio76 Wrote: how can i count  rows of model result ? 
For example :
Code:
$usersModel = new UsersModel();
$users = $usersModel->findAll();
//count all users
?

This should help:
lazy way to count user:  count($users);
Code:
 $count = $userModel->select('*')->countAllResults();
Reply
#6

(02-10-2022, 08:25 AM)demyr Wrote: Yeah, it was for model. You can also check on Documentation page

This isn't for model ....
Reply
#7

You can create a helper function to simplify things:

PHP Code:
if (!function_exists('numRows'))
{
  /**
    * Accepts database result object and returns number of rows found.
    *
    * @param obj $dbObject The returned database object from running query.
    *
    * @return int The row count.
    */
  function numRows($dbObject): int
  
{
      return $dbObject->resultID->num_rows;
  }


Reply
#8

PHP Code:
count($users); 
Reply
#9
Thumbs Up 

(02-10-2022, 07:26 AM)demyr Wrote: Hi,

Code:
public function number_of_x_item($x_id){
$db      = \Config\Database::connect();
$builder = $db->table('your_db_table as dbt');
$query = $builder->select('*')
->where('dbt.item_id', $x_id);

return $query->countAllResults();
}
Thank's, very good help.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB