Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

codeigniter v4 num_rows() Call to undefined method

Num rows not found in the documentation Codeigniter 4.

My method in my model:

public function getListCat()
{
    $listCat = $this->asArray()->where(['id_user' => $session->id])->get();
    return $listCat->num_rows();

i check "Call to undefined method CodeIgniter\Database\MySQLi\Result::num_rows()"

How i can get "num_rows()" data in Codeigniter 4?

like image 314
илья Илья Avatar asked Dec 04 '25 03:12

илья Илья


1 Answers

Boy, I also spent some time researching, but for now, I concluded the following:

According to the framework documentation, there are two methods that it uses to help you count results:

$builder->countAllResults();
$builder->countAll();

https://codeigniter4.github.io/userguide/database/query_builder.html#limiting-or-counting-results

However, there are some discussions in the codeigniter forum about the best way to do this, since theoretically, $builder->countAllResults() or CountAll() would execute another query against the database.

Working for some time with CI4, I noticed a curiosity: If you call get() on your model and on the controller call $queryVarHoldingModelMethodCall->resultID->num_rows - it will show the number of lines in the same way! I believe that, in this way, only a query is executed in the database, since the query object you will be able to call in the controller using $queryVarHoldingModelMethodCall->getRow() or $queryVarHoldingModelMethodCall->getResult()

In your example I would call

public function getListCat()
{
    return $this->asArray()->where(['id_user' => $session->id])->get();
}

And in your controller you can:

$listCatModel     = new \App\Models\ListCatModel(); // call your Model
$listCat          = $listCatModel->getListCat(); // execute method
$listCat_num_rows = $listCat->resultID->num_rows; // num_rows object
$listCatResults   = $listCat->getResult(); // or ->getRow()

You can check what values are you passing by:

var_dump($listCat);
var_dump($listCat->resultID->num_rows);
var_dump($listCat->getRow());
// exit();
// and maybe an exit(); to stop code execution on your vars values and print them for testing

// Let me know how you did it and if it worked, since we don't have enough documentation so far. I am rewriting my first app from CI3 to CI4 and in general it decreased 1/3 of the original code. Working and looking forward to seeing the end result. Good luck out there! Best regards

like image 88
Felipe Lima Avatar answered Dec 05 '25 17:12

Felipe Lima



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!