使用 Zend_DB_Table 选择查询 [英] select queries with Zend_DB_Table
问题描述
我有一个类似下面的代码
I have a code something like following
class Application_Model_Company extends Zend_Db_Table_Abstract {
protected $_name = 'companies';
private $id;
private $name;
private $shortName;
private $description;
public static function getAllCompanies() {
$companyObj = new self();
$select = $companyObj->select()->order(array('name'));
$rows = $companyObj->fetchAll($select);
if($rows) {
$companies = array();
foreach($rows as $row) {
$company = new self();
$company->id = $row->id;
$company->name = $row->name;
$company->shortName = $row->short_name;
$company->description = $row->description;
$companies[] = $comapny;
}
// return Company Objects
return $companies;
}else
throw new Exception('Oops..');
}
}
我需要从 getAllCompanies() 函数返回公司对象,但它返回 Zend_Db_Table_Row 对象.我该如何纠正?
I need to return Company Objects from getAllCompanies() function, But it returns Zend_Db_Table_Row Object. How do I correct this?
推荐答案
你的 Model 类不应该扩展 table 类.表类是分开的.如果从 Zend_Db 扩展任何东西,您的模型应该扩展行类.此外,您不应该直接将检索方法放在模型类上,它们会放在表类上.
Your Model class shouldnt extend the table class. The table class is separate. Your Model should extend the row class if extending anything from Zend_Db at all. Also you shouldnt put retrieval methods on your Model classes directly, they would go on the table classes.
这是因为在您在这里尝试使用的范式中,模型表示单行数据,表类将表表示为数据存储库,行集类表示行(或模型)的集合.
This is because in the paradigm youre trying to use here, a Model represents a single Row of data, the Table class represents the table as a repository of data, and the Rowset class represents a collection of Rows (or Models).
要正确实施您在问题中所描述的内容,您可以执行以下操作:
To properly implement what you are describing in your question you would do something like the following:
class Application_Model_DbTable_Company extends Zend_Db_Table_Abstract
{
// table name
protected $_name = 'company';
protected _$rowClass = 'Application_Model_Company';
// your custom retrieval methods
}
class Application_Model_Company extends Zend_Db_Table_Row
{
protected $_tableClass = 'Application_Model_DbTable_Company';
// custom accessors and mutators
}
然而,实际上推荐使用某种数据映射器模式的实现.查看快速入门,了解有关简化的全面教程实施.
However, using some kind of implementation of the Data Mapper pattern is whats actually recommended. Check out the Quickstart for a thorough tutorial on a simplified implementation.
这篇关于使用 Zend_DB_Table 选择查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!