我发现解决方案 whitch 现在对我来说非常有效。我所需要的就是使用 PDO。这是我现在的代码:
$this->db->conn_id->setAttribute(PDO::ATTR_FETCH_TABLE_NAMES, 1);
$query = $this->db->query("SELECT * FROM comments c LEFT JOIN users u ON u.user_id = c.user_id");
foreach ($query->result_array() as $row)
{
$comment = row2object($row, 'Comment', 'c');
$comment->user = row2object($row, 'User', 'u');
$comments[] = $comment;
}
和 row2object() 助手:
/**
* Row to object
* application/helpers/row2object_helper.php
*
* @param array $row
* @param string $class
* @param string $from_table alias of table name
*/
function row2object(&$row, $class, $from_table)
{
$object = new $class;
foreach($row as $key => $value)
{
list($table, $column) = explode(".", $key);
if($table == $from_table)
{
$object->{$column} = $value;
unset($row[$key]);
}
elseif ($table == "" && substr($key, 1, strlen($from_table)) == $from_table)
{
$column = substr($key, strlen($from_table) + 2);
$object->{$column} = $value;
unset($row[$key]);
}
}
return $object;
}