ThinkPHP 3.2.3 视图模型的使用
生活随笔
收集整理的這篇文章主要介紹了
ThinkPHP 3.2.3 视图模型的使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
ThinkPHP 3.2.3 試圖模型的手冊地址是:http://www.kancloud.cn/manual/thinkphp/1781
?
實例
需求:在博客列表頁讀取博客的(id、標題、摘要、發布時間、點擊次數)等信息以及該篇博文所屬分類的(分類名)等信息
數據表:
crm_blog
+---------+----------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------+----------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | title | varchar(30) | NO | | | | | summary | varchar(255) | NO | | | | | content | text | NO | | NULL | | | time | int(10) unsigned | NO | | 0 | | | click | smallint(6) unsigned | NO | | 0 | | | cid | int(10) unsigned | NO | MUL | NULL | | | del | tinyint(1) unsigned | NO | | 0 | | +---------+----------------------+------+-----+---------+----------------+?
crm_cate
+-------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | name | char(20) | NO | | | | | pid | int(10) unsigned | NO | MUL | 0 | | | sort | smallint(6) | NO | | 100 | | +-------+------------------+------+-----+---------+----------------+?
crm_blog 和 crm_cate 是多對一的關系(BELONGS_TO)
?
在 Home 模塊的 Model(./Application/Home/Model)下創建 BlogViewModel.class.php
<?php namespace Home\Model; use Think\Model\ViewModel; /** 視圖模型*/class BlogViewModel extends ViewModel{protected $viewFields = array('blog'=>array('id','title','summary','click','time','_type'=>'LEFT' //關聯方式,默認是 INNER),'cate'=>array('name'=>'cate_name','_on'=>'blog.cid = cate.id' //關聯條件 ));public function get_all($where,$limit) {return $this->where($where)->limit($limit)->select();} }?
控制器 ./Application/Home/Controller/ListController.class.php
<?php namespace Home\Controller; use Think\Controller; use Admin\Common\Category; use Think\Page;class ListController extends Controller{//列表頁public function index() {$id = (int)$_GET['id'];$cate = M('cate')->order('sort')->select();//分類名稱$this->cate_name = M('cate')->where(array('id'=>$id))->getField('name');//通過父id遞歸查出子id$cids = Category::get_children_id($cate, $id);$cids[] = $id;//分頁$where = array('cid'=>array('IN',$cids)); $count = M('blog')->where($where)->count(); $page = new Page($count,1);$limit = $page->firstRow.','.$page->listRows;$this->page = $page->show();//使用試圖模型$this->blog = D('BlogView')->get_all($where,$limit);//echo D('BlogView')->getLastSql();//一條聯合查詢語句 SELECT blog.id AS id,blog.title AS title,blog.summary AS summary,blog.click AS click,blog.time AS time,cate.name AS cate_name FROM crm_blog blog LEFT JOIN crm_cate cate ON blog.cid = cate.id WHERE `cid` IN ('13','12','11',4)$this->display();} }?
缺陷:在列表頁分頁完成之后,分頁的鏈接并不是 URL 重寫之后的鏈接,待改進。
總結
以上是生活随笔為你收集整理的ThinkPHP 3.2.3 视图模型的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Bugly 技术干货】Android开
- 下一篇: 动态规划算法php,php算法学习之动态