簡體   English   中英

返回CodeIgniter 3中的模型對象數組而不是數組數組

[英]Return array of model objects instead of array of arrays in CodeIgniter 3

我有一個CodeIgniter模型:

<?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';
    }
}
?>

list_persons()函數非常自我解釋。 它從persons數據庫表中獲取所有結果。

目前它返回數組列表中的結果,如下所示:

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"
  }
}

是否可以讓函數list_persons()返回:

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

這樣我就可以使用我在Person_model編寫的自定義函數,例如:

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

提前致謝。

像這樣更新list_person()方法(使用$query->result() ):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM