Zend_Db_Table Relationships 关联查询实战(二)
来源:互联网 发布:2016淘宝冷门暴力行业 编辑:程序博客网 时间:2024/06/05 05:01
查询文章信息时查询出文章相关的分类信息,其实文章表和分类表应该是属于多对一的关系。
接下来我们来看一对多查询的例子,请确保你已经参考实战(一)中的代码创建了相关的数据表结构,并插入了一定的测试数据;
在实战(一)中我们已经在models/Article.php里指定了文章表和分类表的关联信息,相关代码如下:
接下来我们来看一对多查询的例子,请确保你已经参考实战(一)中的代码创建了相关的数据表结构,并插入了一定的测试数据;
在实战(一)中我们已经在models/Article.php里指定了文章表和分类表的关联信息,相关代码如下:
复制内容到剪贴板
PHP代码:
class Article extends Zend_Db_Table { protected $_name = 'articles'; protected $_primary = 'id'; protected $_referenceMap = array( 'category' => array( //关联名称 'columns' => 'cat_id', 'refTableClass' => 'Category', 'refColumns' => 'cat_id', ), );}
修改models/Category.php,添加如下方法:
复制内容到剪贴板
PHP代码:
class Category extends Zend_Db_Table {protected $_name = 'categories';protected $_primary = 'cat_id';public function getArticlesById($cat_id){ $select = $this -> select() -> from('articles',array('id','cat_id','title')); $category = $this -> find($cat_id) -> current(); $articles = $category -> findDependentRowset('Article', 'category', $select) -> toArray(); $rowset = $category -> toArray(); $rowset['articles'] = $articles; return $rowset;}}
我们通过Zend_Db_Table_Row_Abstract提供的findDependentRowset()方法从文章表中关联查询出满足当前记录的数据集,该方法返回一个Zend_Db_Table_Rowset_Abstract对象,该方法有三个参数:
$dependentTable: 关联查询时所依赖表的类定义名(上面的示例中为Article);
$ruleKey:默认为null,通过$_referenceMap属性可以添加多个关联规则信息(应该也可以理解为是关联的名称),在这里指定是通过那个关联规则进行关联查询,如果没有指定,则默认使用$_referenceMap的第一个规则;
Zend_Db_Table_Select $select:默认为null,通过此参数我们可以对关联查询的结果进行一定的限制
OK,下面我们在任意控制器中实例化分类表的数据模型,比如在IndexController中:
复制内容到剪贴板
PHP代码:
class IndexController extends Zend_Controller_Action {public function init(){ }public function indexAction(){ $modelCategory = new Category(); //查询分类ID为2的所有文章信息 $articles = $modelCategory -> getArticlesById(2); Zend_Debug::dump($articles);}}
运行程序结果:
复制内容到剪贴板
PHP代码:
array(4) { ["cat_id"] => string(1) "2" ["parent_id"] => string(1) "0" ["name"] => string(6) "分类二" ["articles"] => array(2) { [0] => array(3) { ["id"] => string(1) "3" ["cat_id"] => string(1) "2" ["title"] => string(24) "这是一篇属于分类二的文章" } [1] => array(3) { ["id"] => string(1) "4" ["cat_id"] => string(1) "2" ["title"] => string(24) "这是一篇属于分类二的文章" } }}
- Zend_Db_Table Relationships 关联查询实战(二)
- Zend_Db_Table Relationships 关联查询实战(一)
- 【小结】初学Zend_Db_Table Relationships
- Zend_Db_Table Relationships 用法
- Zend_Db_Table Relationships 翻译和注释
- Zend_Db_Table 表关联
- Zend_DB_Table
- Zend_Db_Table
- zend_Db_Table
- mybatis(二)---关联表查询
- MyBatis 实战-使用 maven 构建(4)-实现关联查询
- EF中的外键以及关联(Foreign Keys and Relationships (Associations))
- 文本查询程序(关联容器使用)二
- mydatis笔记(二)实现关联数据的查询
- Zend_Db_Table的其他操作(删除、修改、sql语句查询)
- 11--MySQL数据查询应用(实战)(二)
- 深入理解mybatis原理(二) 关联查询
- SSM-MyBatis框架关联查询实例二
- Redis VS Memcached
- 程序=算法+数据结构
- 新浪微博移动客户端更新至3.0:引入电商模式
- JadEclipse工具的使用
- Zend_Db_Table Relationships 关联查询实战(一)
- Zend_Db_Table Relationships 关联查询实战(二)
- CentOS 安装apache、mysql、php
- NUnit配置问题
- jQuery基础之四 -- 事件
- Struts2.1.8版本后的Property标签,在源文件中显示为unicode解决办法
- 增大Zen Cart数据字段
- mysql存储过程语法
- 配置文件读取工具类v1.0
- Super Pig游戏开发记录(2)