首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

Zend Framework Zend_Db_Table 表關聯完整實戰指南

     編輯:PHP 綜合知識

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'))
    );
}

二、從關聯表取數據

1. findDependentRowset() - 一對多「一」查「多」

$user1234->findDependentRowset('Bugs');           // 預設第一個關聯
$user1234->findDependentRowset('Bugs', 'Engineer'); // 指定關聯

2. 魔術方法簡寫

$user1234->findBugs();                 // 預設
$user1234->findBugsByEngineer();     // 指定

三、從父表取數據

1. findParentRow() - 多對一「多」查「一」

$bug1->findParentRow('Accounts');           // 預設
$bug1->findParentRow('Accounts', 'Engineer'); // 指定

2. 魔術方法

$bug1->findParentAccounts();
$bug1->findParentAccountsByEngineer();

四、多對多關聯查詢

透過中間表 BugsProducts:

$bug1234->findManyToManyRowset('Products', 'BugsProducts');           // 預設
$bug1234->findManyToManyRowset('Products', 'BugsProducts', 'Bug'); // 指定關聯

魔術方法:

$bug1234->findProductsViaBugsProducts();
$bug1234->findProductsViaBugsProductsByBug();

五、關鍵提示

  • Rule Key(如 Reporter)僅為關聯標識,不需與表名一致。
  • refTableClass 必須填寫類名而非表名。
  • refColumns 為空時自動使用關聯表主鍵。

更多 Zend 相關技術請參考專題:《Zend Framework 入門教程》、《PHP 優秀開發框架總結》、《Yii 框架入門及常用技巧總結》、《ThinkPHP 入門教程》、《PHP 面向對象程序設計入門教程》、《PHP+MySQL 數據庫操作入門教程》及《PHP 常見數據庫操作技巧匯總》。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved