首页 > 开发 > PHP > 正文

Zend Framework教程之Zend_Db_Table表关联实例详解

2024-05-04 22:31:34
字体:
来源:转载
供稿:网友

本文实例讲述了Zend Framework中Zend_Db_Table表关联用法。分享给大家供大家参考,具体如下:

介绍:

在RDBMS中,表之间有着各种关系,有一多对应,多多对应等等。

Zend框架提供了一些方法来方便我们实现这些关系。

定义关系:

下面是本文用的例子的关系定义:

<?phpclass Accounts extends Zend_Db_Table_Abstract{  protected $_name      = 'accounts';  protected $_dependentTables = array('Bugs');}classclass  protected  protectedclass  protected}Products extends Zend_Db_Table_Abstract{  protected $_name      = 'products';  protected $_dependentTables = array('BugsProducts');}Bugs extends Zend_Db_Table_Abstract{  protected $_name      = 'bugs';$_dependentTables = array('BugsProducts');$_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')    )  );}BugsProducts extends Zend_Db_Table_Abstract{  protected $_name = 'bugs_products';$_referenceMap  = array(    'Bug' => array(      'columns'      => array('bug_id'),      'refTableClass'   => 'Bugs',      'refColumns'    => array('bug_id')    ),    'Product' => array(      'columns'      => array('product_id'),      'refTableClass'   => 'Products',      'refColumns'    => array('product_id')    )  );

我们看到例子中定义了四个类:Accounts,Products,Bugs,BugsProducts。其中Accounts,Products和Bugs是三个实体表,而BugsProducts是关系表。

我们再来分析一下这三个实体,一个Account有多个Bug,他们之间是一对多的关系,而Bug和Product是多对多的关系。

$_dependentTables是一个与该对象关联的对象名,这里注意,要写对象名而不是关联的数据库名。

$_referenceMap数组用来定义和其他表的关系,在这里可以设置和那些表有关系,有什么样的关系。第一个设置的是Rule Key,也就是上面例子的'Reporter', 'Engineer'之类的。Rule Key的作用其实就是一个关系的名字,并不需要和其他数据库表名或者其他对象名的名字一样。只是为了标记的,在后面的时候,我们可以看到这个Rule Key的作用。

每一个Rule下面都有如下的一些定义:(没有特殊说明,都以如上'Reporter'关系进行说明)

columns=> 设置和别的表关联的字段名,如上的'report_by'就是数据库中表Bugs的report_by字段。这里只有一个字段,也可以设置多个字段。

refTableClass=>用于设置与这个表发生关系的表。这里要注意,一定使用目标表的对象的名字而不是表名字,例子中就和'Account'对象发生了关联。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表