ThinkPHP 数据库操作之数据表模型和基础模型 ( Model )
一、定義數據表模型
1.模型映射
要測試數據庫是否正常連接,最直接的辦法就是在當前控制器中實例化數據表,然后使用 dump 函數輸出,查看數據庫的鏈接狀態。代碼:
public function testdb(){$obj=M("User");dump($obj); }此時瀏覽器輸出:
object(Model)#5 (20) {
["_extModel:private"] => NULL
["db:protected"] => object(DbMysql)#7 (18) {
["dbType:protected"] => string(5) "MYSQL"
["autoFree:protected"] => bool(false)
["model:protected"] => string(7) "_think_"
["pconnect:protected"] => bool(false)
["queryStr:protected"] => string(28) "SHOW COLUMNS FROM `tpk_user`"
["modelSql:protected"] => array(1) {
["user"] => string(28) "SHOW COLUMNS FROM `tpk_user`"
}
["lastInsID:protected"] => NULL
["numRows:protected"] => int(2)
["numCols:protected"] => int(0)
["transTimes:protected"] => int(0)
["error:protected"] => string(0) ""
["linkID:protected"] => array(1) {
[0] => resource(27) of type (mysql link)
}
["_linkID:protected"] => resource(27) of type (mysql link)
["queryID:protected"] => resource(28) of type (mysql result)
["connected:protected"] => bool(true)
["comparison:protected"] => array(10) {
["eq"] => string(1) "="
["neq"] => string(2) "<>"
["gt"] => string(1) ">"
["egt"] => string(2) ">="
["lt"] => string(1) "<"
["elt"] => string(2) "<="
["notlike"] => string(8) "NOT LIKE"
["like"] => string(4) "LIKE"
["in"] => string(2) "IN"
["notin"] => string(6) "NOT IN"
}
["selectSql:protected"] => string(96) "SELECT%DISTINCT% %FIELD% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT% %UNION%%COMMENT%"
["bind:protected"] => array(0) {
}
}
["pk:protected"] => string(2) "id"
["tablePrefix:protected"] => string(4) "tpk_"
["name:protected"] => string(4) "user"
["dbName:protected"] => string(0) ""
["connection:protected"] => string(0) ""
["tableName:protected"] => string(0) ""
["trueTableName:protected"] => string(8) "tpk_user"
["error:protected"] => string(0) ""
["fields:protected"] => array(5) {
[0] => string(2) "id"
[1] => string(8) "username"
["_autoinc"] => bool(true)
["_pk"] => string(2) "id"
["_type"] => array(2) {
["id"] => string(7) "int(11)"
["username"] => string(11) "varchar(20)"
}
}
["data:protected"] => array(0) {
}
["options:protected"] => array(0) {
}
["_validate:protected"] => array(0) {
}
["_auto:protected"] => array(0) {
}
["_map:protected"] => array(0) {
}
["_scope:protected"] => array(0) {
}
["autoCheckFields:protected"] => bool(true)
["patchValidate:protected"] => bool(false)
["methods:protected"] => array(13) {
[0] => string(5) "table"
[1] => string(5) "order"
[2] => string(5) "alias"
[3] => string(6) "having"
[4] => string(5) "group"
[5] => string(4) "lock"
[6] => string(8) "distinct"
[7] => string(4) "auto"
[8] => string(6) "filter"
[9] => string(8) "validate"
[10] => string(6) "result"
[11] => string(4) "bind"
[12] => string(5) "token"
}
}
http://127.0.0.26/index.php/index/testdb
object(Model)#5 (20) {["_extModel:private"] => NULL["db:protected"] => object(DbMysql)#7 (18) {["dbType:protected"] => string(5) "MYSQL"["autoFree:protected"] => bool(false)["model:protected"] => string(7) "_think_"["pconnect:protected"] => bool(false)["queryStr:protected"] => string(28) "SHOW COLUMNS FROM `tpk_user`"["modelSql:protected"] => array(1) {["user"] => string(28) "SHOW COLUMNS FROM `tpk_user`"}["lastInsID:protected"] => NULL["numRows:protected"] => int(2)["numCols:protected"] => int(0)["transTimes:protected"] => int(0)["error:protected"] => string(0) ""["linkID:protected"] => array(1) {[0] => resource(27) of type (mysql link)}["_linkID:protected"] => resource(27) of type (mysql link)["queryID:protected"] => resource(28) of type (mysql result)["connected:protected"] => bool(true)["comparison:protected"] => array(10) {["eq"] => string(1) "="["neq"] => string(2) "<>"["gt"] => string(1) ">"["egt"] => string(2) ">="["lt"] => string(1) "<"["elt"] => string(2) "<="["notlike"] => string(8) "NOT LIKE"["like"] => string(4) "LIKE"["in"] => string(2) "IN"["notin"] => string(6) "NOT IN"}["selectSql:protected"] => string(96) "SELECT%DISTINCT% %FIELD% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT% %UNION%%COMMENT%"["bind:protected"] => array(0) {}}["pk:protected"] => string(2) "id"["tablePrefix:protected"] => string(4) "tpk_"["name:protected"] => string(4) "user"["dbName:protected"] => string(0) ""["connection:protected"] => string(0) ""["tableName:protected"] => string(0) ""["trueTableName:protected"] => string(8) "tpk_user"["error:protected"] => string(0) ""["fields:protected"] => array(5) {[0] => string(2) "id"[1] => string(8) "username"["_autoinc"] => bool(true)["_pk"] => string(2) "id"["_type"] => array(2) {["id"] => string(7) "int(11)"["username"] => string(11) "varchar(20)"}}["data:protected"] => array(0) {}["options:protected"] => array(0) {}["_validate:protected"] => array(0) {}["_auto:protected"] => array(0) {}["_map:protected"] => array(0) {}["_scope:protected"] => array(0) {}["autoCheckFields:protected"] => bool(true)["patchValidate:protected"] => bool(false)["methods:protected"] => array(13) {[0] => string(5) "table"[1] => string(5) "order"[2] => string(5) "alias"[3] => string(6) "having"[4] => string(5) "group"[5] => string(4) "lock"[6] => string(8) "distinct"[7] => string(4) "auto"[8] => string(6) "filter"[9] => string(8) "validate"[10] => string(6) "result"[11] => string(4) "bind"[12] => string(5) "token"} }如果沒有提示錯誤即為成功。
M("User") 就是模型映射,M 函數等于 new Model() ,Model 類是模型的基類,也是數據庫操作的基類, "User" 是該類的一個成員屬性,表示模型名稱,模型名稱與數據庫中的數據表進行映射。注意:User "U" 要大寫,數據庫中此時應該存在一張 user 表,系統會根據配置文件中的設置給 user 表添加前綴,例如 tpk_user。如果不需要為表添加前綴,將模型名稱首字母改為小寫,例如 M("user")。
2.自定義模型
D 函數用于快速實例化自定義模型,可以進行復雜的數據庫操作,比如數據檢驗、數據緩存、數據加工等。自定義模型存放在 Lib/Model 目錄下,例如為數據表 tpk_article 數據表建立模型映射,則需要創建 ArticleModel.class.php,然后使用 D 函數進行實例化,ArticleModel 模型將與 tpk_article 表進行映射。
例:使用 select() 輸出 tpk_article 表的數據 ( select() 方法用于列出所有符合條件的數據 ) :
class IndexAction extends Action { public function article(){$obj=D("Article");$rows=$obj->select(); dump($rows);} }瀏覽器輸出:
array(6) {
[0] => array(7) {
["id"] => string(1) "1"
["title"] => string(4) "test"
["content"] => string(12) "test_content"
["category"] => string(13) "test_category"
["area"] => string(6) "北京"
["add_user"] => string(5) "admin"
["add_time"] => string(19) "2014-11-20 23:03:44"
}
[1] => array(7) {
["id"] => string(1) "2"
["title"] => string(12) "吼吼吼吼"
["content"] => string(18) "任溶溶柔然人"
["category"] => string(14) "test_category2"
["area"] => string(6) "河北"
["add_user"] => string(5) "admin"
["add_time"] => string(19) "2014-11-22 15:16:12"
}
[2] => array(7) {
["id"] => string(1) "4"
["title"] => string(7) "test2_m"
["content"] => string(4) "haha"
["category"] => string(0) ""
["area"] => string(6) "福建"
["add_user"] => NULL
["add_time"] => string(19) "2014-11-22 11:44:26"
}
[3] => array(7) {
["id"] => string(1) "5"
["title"] => string(2) "22"
["content"] => NULL
["category"] => string(0) ""
["area"] => string(6) "福建"
["add_user"] => NULL
["add_time"] => string(19) "2014-11-22 12:40:58"
}
[4] => array(7) {
["id"] => string(1) "6"
["title"] => string(1) "1"
["content"] => string(1) "2"
["category"] => string(0) ""
["area"] => string(6) "福建"
["add_user"] => NULL
["add_time"] => NULL
}
[5] => array(7) {
["id"] => string(1) "7"
["title"] => string(6) "lalala"
["content"] => string(6) "hohoho"
["category"] => string(0) ""
["area"] => string(6) "北京"
["add_user"] => NULL
["add_time"] => NULL
}
}
http://127.0.0.26/index.php/index/article
array(6) {[0] => array(7) {["id"] => string(1) "1"["title"] => string(4) "test"["content"] => string(12) "test_content"["category"] => string(13) "test_category"["area"] => string(6) "北京"["add_user"] => string(5) "admin"["add_time"] => string(19) "2014-11-20 23:03:44"}[1] => array(7) {["id"] => string(1) "2"["title"] => string(12) "吼吼吼吼"["content"] => string(18) "任溶溶柔然人"["category"] => string(14) "test_category2"["area"] => string(6) "河北"["add_user"] => string(5) "admin"["add_time"] => string(19) "2014-11-22 15:16:12"}[2] => array(7) {["id"] => string(1) "4"["title"] => string(7) "test2_m"["content"] => string(4) "haha"["category"] => string(0) ""["area"] => string(6) "福建"["add_user"] => NULL["add_time"] => string(19) "2014-11-22 11:44:26"}[3] => array(7) {["id"] => string(1) "5"["title"] => string(2) "22"["content"] => NULL["category"] => string(0) ""["area"] => string(6) "福建"["add_user"] => NULL["add_time"] => string(19) "2014-11-22 12:40:58"}[4] => array(7) {["id"] => string(1) "6"["title"] => string(1) "1"["content"] => string(1) "2"["category"] => string(0) ""["area"] => string(6) "福建"["add_user"] => NULL["add_time"] => NULL}[5] => array(7) {["id"] => string(1) "7"["title"] => string(6) "lalala"["content"] => string(6) "hohoho"["category"] => string(0) ""["area"] => string(6) "北京"["add_user"] => NULL["add_time"] => NULL} }例2:讓 tpk_article 表的內容根據客戶所在的地區顯示當地的新聞:
ArticleModel.class.php:
<?php class ArticleModel extends Model{public function article(){$rows=$this->where("area='{$this->checkUserArea()}'")->select();return $rows;}protected function checkUserArea(){return "北京"; }控制器代碼:
IndexAction.class.php:
<?php class IndexAction extends Action {$obj=D("Article");$rows=$obj->article();$this->assign("list",$rows);$this->display();同時視圖代碼:
TPL/Index/article.html:
<!DOCTYPE html> <html> <body><volist name="list" id="vo"><li><{$vo.title}> - <{$vo.area}> - <{$vo.content}></li> </volist></body> </html>附:數據表 tpk_article 的表結構為:
總結:自定義模型映射,一個模型對應一個數據表,所有增刪改查都在模型類中完成。M 實例化的參數是數據庫的表名,D 實例化的是自己在 model 文件夾下建立的模型文件。
3.create 方法
TP 對數據的插入和更新都做了高度封裝:提供了 create() 方法用于創建數據對象。
概念:數據對象 —— 數據字段與數據表之間的關系,數據會被映射為類成員,再與數據表映射,最后實現數據的插入或更新。
create() 方法是連貫操作、CURD 操作的集合 ( 包括數據創建、數據檢驗、表單驗證、自動完成等 )。
cerate() 的數據源由 POST 表單提供,比如表單中有 username 表單元素,則該元素會被自動映射為數據表中的 username 字段。數據對象創建成功以后,對象被存放于內存中。
例:添加數據
控制器:IndexAction,動作:add_article,代碼:
IndexAction.class.php:
<?php class IndexAction extends Action {Public function add_article(){$this->display();} }視圖:?Tpl/Index/add_article.html:
<!DOCTYPE html> <html> <body><form method="post" action="__URL__/add"><input type="text" name="title" placeholder="標題"><br><br><textarea name="content" id="content" placeholder="內容"></textarea><br><br><input type="submit" name="submit" value="提交"></form></body> </html>__URL__/add 表示當前控制器的 add 動作。
add 動作代碼:
<?php class IndexAction extends Action {public function add(){//表單處理$articleObj = M('Article');$articleObj->create();$articleObj->add_time = date("Y-m-d H:i:s",time());if($articleObj->add()){$this->success("數據添加成功");}else{$this->error("數據添加失敗");} }例子結束。
4.模型屬性( Model )
?_map 屬性:字段映射
為了避免前臺表單元素與數據庫字段名相同而使數據庫字段暴露,可以修改前臺表單元素的 name,同時在 Model 中使用 _map 屬性。代碼:
視圖:Tpl/Index/add_article.html:
<!DOCTYPE html> <html> <body><form method="post" action="__URL__/add"><input type="text" name="subject" placeholder="標題"><br><br><textarea name="textEdit" id="content" placeholder="內容"></textarea><br><br> <input type="submit" name="submit" value="提交"></form></body> </html>模型:ArticleModel.class.php:
<?php class ArticleModel extends Model{//使用_map屬性(字段映射)將表單元素映射為相應表字段protected $_map = array("subject"=>"title","textEdit"=>"content");}控制器:IndexAction.class.php:
<?phpclass IndexAction extends Action {$articleObj = D("Article");$articleObj->create();$articleObj->add_time = date("Y-m-d H:i:s",time());if($articleObj->add()){$this->success("數據添加成功");}else{$this->error("數據添加失敗");} }例子結束。
二、基礎模型
1.連貫操作
連貫方法除了 select() 方法外,其他的連貫方法不區分前后順序。
例:
$rows=$obj->where("add_user='dee'")->order("add_time desc")->limit(10)->select();2.CURD
① 創建數據 add()
<?phpclass IndexAction extends Action {public function post(){$articleObj = D("Article");$data['title'] = $_POST['subject'];$data['content'] = $_POST['textEdit'];$data['add_time'] = date("Y-m-d H:i:s",time());if($articleObj->add($data)){$this->success("數據添加成功");}else{$this->error("數據添加失敗");}} }另一個例子:
<?phpclass IndexAction extends Action {public function post(){$articleObj = D("Article");$data['title'] = $_POST['subject'];$data['content'] = $_POST['textEdit'];$data['add_time'] = date("Y-m-d H:i:s",time());if($articleObj->data($data)->add()){$this->success("數據添加成功");}else{$this->error("數據添加失敗");}} }② 更新數據 save()
<?phpclass IndexAction extends Action {public function post2(){$articleObj = M("Article");$data['id'] = 2;$data['title'] = $_POST['subject'];$data['content'] = $_POST['textEdit'];$data['area'] = '河北';$data['add_time'] = date("Y-m-d H:i:s",time());if($articleObj->save($data)){$this->success("數據修改成功");}else{$this->error("數據修改失敗");}} }③ 讀取數據 select 和 getFiled
getField 例子:
<?phpclass IndexAction extends Action {public function post3(){$articleObj = M("Article");if($articleObj->where("id=3")->setField("content","{$_POST['subject']}")){$this->success("數據修改成功");}else{$this->error("數據修改失敗");}} }④ 刪除數據 delete
<?phpclass IndexAction extends Action {public function delete(){$articleObj = M("Article");if($articleObj->where("id=".$_GET['id'])->delete()){$this->success("數據刪除成功");}else{$this->error("數據刪除失敗");}} }3.查詢語言
例子:
<?phpclass IndexAction extends Action {public function archives(){$obj = M("Archives"); // $data['writer'] = array("eq","網絡營銷中心"); // $data['title'] = array("like","精誠%");$data['id'] = array("lt","100");$rows=$obj->where($data)->select();$count=$obj->where($data)->count();$tb=C("DB_PREFIX");$this->assign("list",$rows);$this->assign("count",$count);$this->assign("tb",$tb);$this->display("Article");}public function archives2(){$obj = M("Archives");$data['id'] = array(array("lt","1034"),array("GT","1029"),"and");$rows=$obj->where($data)->select();$this->assign("list",$rows);$this->display("Article");} }可以在控制器中使用?echo $obj->getLastSql(); 查看轉換后的 SQL 語句。
參考資料:《PHP MVC 開發實戰》
總結
以上是生活随笔為你收集整理的ThinkPHP 数据库操作之数据表模型和基础模型 ( Model )的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Namespace declaratio
- 下一篇: 买什么二手车最值?