Zend Framework 的 Zend_Db_Table 提供聲明式關聯映射,支援一對多、多對多等關係。本文以 Bug 追蹤系統為例,詳細講解關聯定義、依賴查詢、父表查詢、多對多查詢及魔術方法用法。
四個表:Accounts、Products、Bugs、BugsProducts(關聯表)。關鍵屬性:
$_dependentTables:聲明被依賴的表(如 Accounts 依賴 Bugs)。$_referenceMap:定義外鍵關聯,包含 columns(本表欄位)、refTableClass(關聯類名)、refColumns(關聯表欄位)、onDelete/onUpdate(級聯動作)。class Bugs extends Zend_Db_Table_Abstract {
protected $_name = 'bugs';
protected $_dependentTables = array('BugsProducts');
protected $_referenceMap = array(
'Reporter' => array('columns'=>'reported_by', 'refTableClass'=>'Accounts', 'refColumns'=>'account_name'),
'Engineer' => array('columns'=>'assigned_to', 'refTableClass'=>'Accounts', 'refColumns'=>'account_name'),
'Verifier' => array('columns'=>array('verified_by'), 'refTableClass'=>'Accounts', 'refColumns'=>array('account_name'))
);
}
$user1234->findDependentRowset('Bugs'); // 預設第一個關聯
$user1234->findDependentRowset('Bugs', 'Engineer'); // 指定關聯
$user1234->findBugs(); // 預設 $user1234->findBugsByEngineer(); // 指定
$bug1->findParentRow('Accounts'); // 預設
$bug1->findParentRow('Accounts', 'Engineer'); // 指定
$bug1->findParentAccounts(); $bug1->findParentAccountsByEngineer();
透過中間表 BugsProducts:
$bug1234->findManyToManyRowset('Products', 'BugsProducts'); // 預設
$bug1234->findManyToManyRowset('Products', 'BugsProducts', 'Bug'); // 指定關聯
魔術方法:
$bug1234->findProductsViaBugsProducts(); $bug1234->findProductsViaBugsProductsByBug();
refTableClass 必須填寫類名而非表名。refColumns 為空時自動使用關聯表主鍵。更多 Zend 相關技術請參考專題:《Zend Framework 入門教程》、《PHP 優秀開發框架總結》、《Yii 框架入門及常用技巧總結》、《ThinkPHP 入門教程》、《PHP 面向對象程序設計入門教程》、《PHP+MySQL 數據庫操作入門教程》及《PHP 常見數據庫操作技巧匯總》。