作者:Florence珠宝定制 | 来源:互联网 | 2013-06-18 23:51
ThinkPHP 数据库视图模型
注意:本文中的视图,是指数据库视图模型,而非 ThinkPHP 中的 View
视图类实现。
数据库视图是指从一个或几个基本表中根据用户需要,提取出需要的数据列而做成一个虚表。这样就不必根据 a 表数据再去查询 b 表,c
表... 等有关系的表而方便的一次性将数据查询出来。
视图在有些数据库下面并不被支持,ThinkPHP
模拟实现了数据库的视图,该功能可以用于多表联合查询。
要在 ThinkPHP 中使用视图模型,只需要继承 ViewModel,然后设置
viewFields 属性,使用 D方法实例化模型 即可。
视图模型实例
现有 user 表和 article 表如下(表前缀为
test_):
user 用户表(略):
article 文章表(略):
创建视图模型文件
-
-
class ArticleViewModel extends ViewModel{
-
public $viewFields = array(
-
'article'=>array('aid','title','content','uid'),
-
'user'=>array('username','_on'=>'article.uid=user.uid'),
-
);
-
}
-
?>
在该视图模型文件中,模型类继承 ViewModel
视图模型,并定义 $viewFields 属性,每个元素包括了数据表及对应要查询的字段。在每个表元素中,通过定义 _on
元素来定义关联查询条件。
将该文件保存为 Lib/Model/ArticleViewModel.class.php 。
在 Action
操作中使用视图模型
在模块操作中,使用 D 方法来实例化视图模型:
-
-
class ArticleAction extends Action{
-
public function index(){
-
header("Content-Type:text/html; charset=utf-8");
-
$Dao = D('ArticleView'); // 实例化视图
-
$article_list = $Dao->select();
-
print_r($article_list);
-
echo '
';
-
// 打印出执行的 SQL 语句
-
echo '执行的 SQL 语句为:'.$Dao->getLastSql();
-
}
-
}
-
?>
访问该方法,打印出结果如下:
-
Array
-
(
-
[0] => Array
-
(
-
[aid] => 1
-
[title] => 文章1
-
[content] => 文章1具体内容……
-
[username] => admin
-
)
-
-
[1] => Array
-
(
-
[aid] => 2
-
[title] => 文章2
-
[content] => 文章2具体内容……
-
[username] => Jack
-
)
-
-
)
执行的 SQL 语句为:
-
SELECT article.aid AS aid,article.title AS title,article.content AS content,
-
article.uid AS uid,user.username AS username FROM test_article article JOIN test_user user ON
-
article.uid=user.uid
从上面的结果可以看出,视图模型是利用了 JOIN查询 模拟了数据库视图的实现,将多张表的数据汇聚到一起。