注意:本文中的視圖,是指數(shù)據(jù)庫視圖模型,而非 ThinkPHP 中的 View 視圖類實現(xiàn).
數(shù)據(jù)庫視圖是指從一個或幾個基本表中根據(jù)用戶需要,提取出需要的數(shù)據(jù)列而做成一個虛表,這樣就不必根據(jù) a 表數(shù)據(jù)再去查詢 b 表,c 表... 等有關系的表而方便的一次性將數(shù)據(jù)查詢出來.
視圖在有些數(shù)據(jù)庫下面并不被支持,ThinkPHP 模擬實現(xiàn)了數(shù)據(jù)庫的視圖,該功能可以用于多表聯(lián)合查詢.
要在 ThinkPHP 中使用視圖模型,只需要繼承 ViewModel,然后設置 viewFields 屬性,使用 D方法實例化模型 即可.
視圖模型實例
現(xiàn)有 user 表和 article 表如下(表前綴為 test_):
- uid username password email regdate
- 1 admin b7e591c246d010bb2ccd77d52490c85e [email protected] 1277992339
- 2 小明 a193686a53e4de85ee3f2ff0576adf01 [email protected] 1278063917
- 3 Jack 0193686a35e4de85ee3f2ff0567adf49 [email protected] 1278061380
- aid title content add_time cid uid
- 1 文章1 文章1正文內容…… 1277993339 1 1
- 2 文章2 文章2正文內容…… 1277994339 2 3
創(chuàng)建視圖模型文件:
- <?php
- class ArticleViewModel extends ViewModel{
- public $viewFields = array(
- 'article'=>array('aid','title','content','uid'),
- 'user'=>array('username','_on'=>'article.uid=user.uid'),
- );
- }
- ?>
在該視圖模型文件中,模型類繼承 ViewModel 視圖模型,并定義 $viewFields 屬性,每個元素包括了數(shù)據(jù)表及對應要查詢的字段,在每個表元素中,通過定義 _on 元素來定義關聯(lián)查詢條件.
將該文件保存為 Lib/Model/ArticleViewModel.class.php.
在 Action 操作中使用視圖模型
在模塊操作中,使用 D 方法來實例化視圖模型:
- <?php
- 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 '<br /><br />';
- // 打印出執(zhí)行的 SQL 語句
- echo '執(zhí)行的 SQL 語句為:'.$Dao->getLastSql();
- }
- }?>
訪問該方法,打印出結果如下:
- Array(
- [0] => Array(
- [aid] => 1,
- [title] => 文章1,
- [content] => 文章1具體內容……,
- [username] => admin,
- )
- [1] => Array(
- [aid] => 2,
- [title] => 文章2,
- [content] => 文章2具體內容……,
- [username] => Jack,
- )
- )
執(zhí)行的 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
新聞熱點
疑難解答
圖片精選