5

我目前正在使用 Codeigniter 框架。在下面的代码中,我想获取一个Animal_model对象,而不是一个stdClass对象。

<?php
class Animal_model extends CI_Model{

    var $idanimal;
    var $name;
    public static $table = 'animals';

    function __construct() {
        parent::__construct();
    }

    function getone(self $animal){
        $query = $this->db->get_where(self::$table, array('id_animal' => $animal->idanimal));

        if($query == FALSE){
            return FALSE;
        }else{
            return $query->row(); // How to get an Animal_model object here? 
        }
    }
}

$lion = new Animal_model();
$lion->idanimal = 25; 
var_dump($lion); // It says "object(Animal_model)".

$lion = $lion->getone($lion);
var_dump($lion); // Now it says "object(stdClass)".

?>

如何转换$query->row()为 Animal_model 对象?

4

5 回答 5

6

CodeIgniter 有内置的功能!

return $query->row(0, 'Animal_model');
于 2012-12-17T15:20:51.767 回答
1
    if($query == FALSE){
        return FALSE;
    }else{
       // How to get an Animal_model object here? 
       $row = $query->row();

       $animal = new Animal_model();
       $animal->idanimal = $row->idanimal;
       $animal->name= $row->name;
       return $animal;
    }

以上将做你想要的,但我认为这不是一个好主意。最好有第二个类,例如Animal不扩展任何可用于表示动物的模型。

class Animal
{
    public name = '';
    public id = 0;

    public function __construct($id, $name)
    {
        $this->id = $id;
        $this->name = $name;
    }
}

在您的模型中,您可以创建 this 的实例并返回它们,而不是返回模型对象。

    if($query == FALSE){
        return FALSE;
    }else{
        $row = $query->row();
        return new Animal($row->idanimal, $row->name);
    }

我还会将getone函数更改为采用 ID,并选择此 ID 匹配的位置:

function getone($id){

通过这种方式,您可以将模型用作动物的管理器,模型处理数据并返回 Animal 对象。

于 2012-12-17T14:49:28.613 回答
0

你的第一个var_dump($lion)是 type object(Animal_model)

然后用现在$lion的结果覆盖 的值,或者 的值,这将返回一个 object( )。$lion->getone($lion); $lionFALSE$query->row()stdClass

$query->row()始终返回一个数据库结果对象(一个stdClass对象)。

你的代码正在做它应该做的事情。

http://ellislab.com/codeigniter/user-guide/database/results.html

请问为什么你需要那个对象是 type 的Animal_model

于 2012-12-17T14:48:20.037 回答
0

而不是 return $query->row(); 您可以实例化 Animal_model 类的对象并将 $query->row() 中的值分配给对象的属性。但我不确定这样做有什么价值。您仍将获得相同的数据。Animal_Model 类中是否有需要在检索行后调用的方法?

侧边栏注释... 您可能希望避免使用“var”来描述您的属性。除非您能想到公共或私人的原因,否则您可能想使用“受保护”。

于 2012-12-17T14:52:21.880 回答
0

如果我理解你的问题;当您调用数据库表而不是单个列数据时,您想要一个自定义类对象(Animal_model 类型)对吗?

首先,当您调用 $query->row() 时,您不会检索 Animal_model 对象。您正在检索数据库行对象。您实际上必须从中提取单个数据实例:

   $row = $query->row(); 

   echo $row->title;
   echo $row->name;
   echo $row->body;

因此,由于您设计类的方式,我建议您创建一个自定义静态函数,该函数将采用数据库行对象的实例并实例化一个新的 Animal_model 实例。或者采用数据库行对象的实例并填充所述对象的字段的方法。

于 2012-12-17T14:59:29.920 回答