Search code examples
phpcodeigniter-4

How to call affected_rows method from ci4 model


I have a model that extends CI4 builtin Model..

use CodeIgniter\Model;
use CodeIgniter\I18n\Time;

class ArticleModel extends Model { .. }

Any idea how do i perform the following?

$this->db->affected_rows();

thinking of getting it after deleting a row, most of the example using custom model, not extending ci4 model.


Solution

  • First, be sure to set your database connection up correctly in app/Config/App.php or in your .env file.
    Then $this->db from the core Model in CI4 doesn't create the connection. You have to create it first then you can perform queries.

    affected_rows() method doesn't exist in CI4, it's now called affectedRows(). So to call it you will enventually come up with something like this :

        // your db connection
        $this->db = \Config\Database::connect();
        // your query
        $this->db->query('MY QUERY');
        // number of affected rows
        $affected_rows = $this->db->affectedRows();