我從Zend Framework開始,我對模型和relathionships(一對多,多對多等)有點困惑。Zend模型和數據庫關係
的「Zend框架快速入門」說要建立一個Zend_Db_Table類,一個數據映射,最後 我們的模型類
假設我們有一個這樣的數據庫:
table A (
id integer primary key,
name varchar(50)
);
table B (
id integer primary key,
a_id integer references A
);
,那我就創建:
Application_Model_DbTable_A extends Zend_Db_Table_Abstract,
Application_Model_AMapper,
Application_Model_A,
Application_Model_DbTable_B extends Zend_Db_Table_Abstract,
Application_Model_BMapper,
Application_Model_B,
,如果我的理解,我給的參考信息存儲在 Application_Model_DbTable_A:
protected $_dependentTables = array('B');
和Application_Model_DbTable_B:
protected $_referenceMap = array(
'A' => array(
'columns' => array('a_id'),
'refTableClass' => 'A',
'refColums' => array('id')
)
);
和我的模型類:
class Application_Model_A
{
protected $_id;
protected $_name;
public function __construct(array $options = null)
{
if(is_array($options)) {
$this->setOptions($options);
}
}
public function __set($name, $value)
{
$method = 'set' . $name;
if (('mapper' == $name) || !method_exists($this, $method)) {
throw new Exception('Invalid property');
}
$this->$method($value);
}
public function __get($name)
{
$method = 'get' . $name;
if (('mapper' == $name) || !method_exists($this, $method)) {
throw new Exception('Invalid property');
}
return $this->$method();
}
public function setOptions(array $options)
{
$methods = get_class_methods($this);
foreach ($options as $key => $value) {
$method = 'set' . ucfirst($key);
if (in_array($method, $methods)) {
$this->$method($value);
}
}
return $this;
}
public function setName($name)
{
$this->_name = (string) $name;
return $this;
}
public function getName()
{
return $this->_name;
}
public function setId($id)
{
$this->_id = (int) $id;
return $this;
}
public function getId()
{
return $this->_id;
}
class Application_Model_B
{
protected $_id;
protected $_a_id;
public function __construct(array $options = null)
{
if(is_array($options)) {
$this->setOptions($options);
}
}
public function __set($name, $value)
{
$method = 'set' . $name;
if (('mapper' == $name) || !method_exists($this, $method)) {
throw new Exception('Invalid property');
}
$this->$method($value);
}
public function __get($name)
{
$method = 'get' . $name;
if (('mapper' == $name) || !method_exists($this, $method)) {
throw new Exception('Invalid property');
}
return $this->$method();
}
public function setOptions(array $options)
{
$methods = get_class_methods($this);
foreach ($options as $key => $value) {
$method = 'set' . ucfirst($key);
if (in_array($method, $methods)) {
$this->$method($value);
}
}
return $this;
}
public function setA_id($a_id)
{
$this->_a_id = (int) $a_id;
return $this;
}
public function getA_id()
{
return $this->_a_id;
}
public function setId($id)
{
$this->_id = (int) $id;
return $this;
}
public function getId()
{
return $this->_id;
}
它是正確的?
你試試吧,它的工作原理?如果不是,你會得到什麼錯誤信息? – markus 2011-03-20 00:08:05
我想他正試圖理解zend框架如何處理多對一和多對多的映射以及可能的級聯效應。 – kjy112 2011-03-20 01:28:00
你可以嘗試減少一半的代碼,並提出更具體的問題。寫下你的大聲思考協議。 – markus 2011-03-20 13:39:46