drwu24647 2013-09-24 00:02
浏览 58
已采纳

使用ORM样式在CodeIgniter中编写模型类

I thought about using an actual ORM like Doctrine, then I figured its download link was even broken...and all tutorials online dated back to 2011. Also I'll have to write yaml files.

Then I start off by trying to write my own model class in ORM style.

I just fill it up with fields and save it to database, which is easy.

But I encounter a problem trying to retrieve data from database.

class User extends CI_Model {

    public $id;
    public $email;
    public $displayName;

 public function save() {
  .....
 }

public function search_by_email($email) {
    $user = new User();
    $this->db->select('email')->from('user')->where('email', $email);
    $result = $this->db->get();
    if ($result->num_rows()==0) {
        return false;
    }else {
        foreach ($result->result() as $field) {

        }
    }
}

I know normally in CodeIgniter, you return $query->result(), well as ORM custom, I'm trying to return an object...Is there a way to do this? What function should I use?

  • 写回答

2条回答 默认 最新

  • douwu8060 2013-09-24 01:49
    关注

    result takes a string that represents a class that it will instantiate and assigned the result data (each field as a property of the object):

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

    regarding your comment, i'm pretty sure that codeigniter has no idea about anything regarding the class you pass to the result method. It looks like it just instantiates it and sets property and valuefor each column/value returned from the db:

    $this->custom_result_object[$class_name][$i] = new $class_name();
    
    foreach ($this->{$_data}[$i] as $key => $value)
    {
        $this->custom_result_object[$class_name][$i]->$key = $value;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化