Returning an array of model objects instead of an array of arrays in CodeIgniter 3

I have a CodeIgniter model:

<?php
class Person_model extends CI_Model {
    public function __construct() {
        $this->load->database();
    }

    public function list_persons() {
        $query = $this->db->get('persons');
        return $query->result_array();
    }

    public function foobar() {
        return 'Custom function here';
    }
}
?>

      

The function list_persons()

is well explained. It fetches all results from a database table persons

.

It currently returns results in a list of arrays, for example:

array(2) {
  [0] => array(3) {
    ["id"] => string(1) "1"
    ["first_name"] => string(6) "Test 1"
  }
  [1] => array(3) {
    ["id"] => string(1) "2"
    ["first_name"] => string(6) "Test 2"
  }
}

      

Is it possible to return a function list_persons()

:

array(2) {
  [0] => Person_model {
    "id" => 1
    "first_name" => "Test 1"
  }
  [1] => Person_model {
    "id" => 2
    "first_name" => "Test 2"
  }
}

      

so that I can use the custom functions I wrote in Person_model

, for example:

foreach($this->person_model->list_persons() as $person) {
    echo $person->foobar();
}

      

Thanks in advance.

+3


source to share


1 answer


Update your method list_person()

like this (use $query->result()

):



public function list_persons() {
    $query = $this->db->get('persons');
    return $query->result('Person_model');
}

      

+5


source







All Articles