开发者

Tying Model to Query Result in CodeIgniter?

开发者 https://www.devze.com 2023-04-08 14:34 出处:网络
Here is what their documentation says You can also pass a string to result() which represents a class to

Here is what their documentation says

You can also pass a string to result() which represents a class to instantiate for each result object (note: this class must be loaded)

$query = $this->db->query("SELECT * FROM users;"); 
foreach ($query->result('User') as $user) {    
    echo $row->name; // call attributes    
    echo $row->reverse_name(); // or methods defined on the 'User' class 
}

Despite the fact that they are echoing $row instead of $user... this does not seem to work for me. Here is my version of testing it

Model

class User extends CI_Model{
    var $first;
    var $last;
..  
    function getName() {
        return $this->first + " " + $this->last;
    }
}   

Controller

class Tester extends CI_Controller {

     public function index() {
          $this->load->model('User');
          $query = $this->db->query('SELECT * from USERS');
          $data = array (
              'regular' => $query->result(),
              'modeled' => $开发者_如何学JAVAquery->result('User')
          );
          $this->load->view('test', $data);
     }
}

View

foreach ($regular as $row) {
    echo "{$row->FIRST} {$row->LAST} <BR/>";
}

echo "<br/>";

foreach ($modeled as $row) {
    echo "{$row->getName()} <BR/>";
}

Is there something that I'm doing wrong or misunderstanding? I would assume that based on their documentation, that if I assign a class to the result set, the class should be populated with the results? Now, how it goes on knowing which field to map to is a mystery to me and may very well be the reason why this doesn't work. I thought perhaps I needed to modify the constructor to do this mapping but I didn't see any documentation as to how I would go about doing that. I tried putting in a parameter for the constructor assuming it was an StdClass array but didn't seem to work.

Any clarifications would be great!


So it dawned on me to check the actual source code of the db_results function and I figured that it's due to the case of the query result columns. And it seems that CI defaults everything to UPPERCASE unless you specify it as lowercase in your query string.

So in conclusion, whatever the case of columns is in your query, should be the case of values in your Model!

Seems ridiculous though... I'll probably see if I can edit the core class to not be case-sensitive. Unless someone has better alternatives.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号