我正在尝试构建一个自定义的ActiveRecord类,并尝试在对象中返回MySQL结果。对象将是模型。 这就是我正在做的事情:
while($object = mysql_fetch_object($result, $this->_model)) {
foreach($object as $key => $val) {
if($this->is_serialized($val)) $object->$key = unserialize($val);
}
$return_value[] = $object;
}
如果我对结果执行了print_r(),我会得到一个空类(没有设置变量或任何变量)。 这是我的模特:
class User extends ActiveRecord {
public $_hasOne = "Profile";
public $_required = array('full_name', 'user_name', 'password', 'country');
public $_unique = array('full_name', 'user_name');
}
我无法弄清楚我做错了什么!
编辑:最后修正了它。在我的Activerecord课程开始时我有这个:
$fields = $this->query("SHOW COLUMNS FROM " . $this->_table);
while($field = mysql_fetch_assoc($fields)) {
$this->_columns[] = $field['Field'];
$this->$field['Field'] = null;
}
将所有值设置为NULL! 有点傻的错误。现在是:
$fields = $this->query("SHOW COLUMNS FROM " . $this->_table);
while($field = mysql_fetch_assoc($fields)) {
$this->_columns[] = $field['Field'];
if(!isset($this->$field['Field'])) $this->$field['Field'] = null;
}
答案 0 :(得分:0)
愚蠢的问题,但是$this->_model
是"User"
正确的(我会回复这个值,它可能会以某种方式解开)。
之后,您的类应该具有与您要表示的列相同名称的字段。所以:
class Foo
{
private $id;
public $val;
public function __toString(){ return "$this->id => $this->val"; }
}
mysql_connect('localhost','root','');
$q = mysql_query('SELECT 1 as id, 2 as val FROM DUAL');
$foo = mysql_fetch_object( $q, 'Foo' );
echo $foo; // 1 => 2
接下来,您无法迭代对象。您需要迭代对象属性:
foreach(get_object_vars($object) as $key => $val) {
if($this->is_serialized($val)) $object->$key = unserialize($val);
}