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 quite self-explained. It fetches all results from persons database table.

Currently it returns results in a list of arrays, like this:

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 let the function list_persons() to return:

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 the Person_model, such as:

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

Thanks in advance.

1 Answer 1

6

Update your list_person() method like this (use $query->result()):

public function list_persons() {
    $query = $this->db->get('persons');
    return $query->result('Person_model');
}
Sign up to request clarification or add additional context in comments.

4 Comments

Nice. However, the class returned is a stdClass instead of a Person_model, which the foobar() cannot be called. Any advise?
I have updated the answer. Pass a string which represents the model class to the $query->result(), for example $query->result('Person_model') to convert it to your model class.
Works perfectly. Thanks!
This is awesome! I never knew about this! Thank you @RendyEkoPrastiyo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.