thinkphp創建對象及數據操作


ThinkPHP有三種創建控制器對象的方式:

  1. 通過命名空間的路徑找到類然后new出來例如:$dx = new \Home\Controller\IndexController();
  2. 通過A快捷函數創建對象A("模塊/控制器")例如: $dx = A("Home\Index");
  3. 通過R快捷函數創建對象並調用方法;R("Index/ShuChu")

ThinkPHP操作數據庫:

首先需要在配置文件中配置數據庫信息

在創建模型對象執行sql語句

創建模型對象有三種方式:

  1. 原始方式需要模型中建模型類,類名必須是數據庫表名,例如:$m = new \Home\Model\InfoModel();
  2. 使用快捷函數D:$m = D("Info");需要注意的是如果沒有模型類可以不加參數,對象就是model父類的對象

  3、使用快捷函數M:$m = M("Nation");

操作數據庫:

首先介紹一下連貫函數,就是返回值是:$this,也就是說返回自身對象,可以繼續調用函數

數據庫操作中基本的函數:select("主鍵值【,主鍵值】")、find("主鍵值"),聚合函數不是連貫函數。

具體用法如下如下:(可以參考手冊)

操作數據庫
$attr = $m->select(); //查詢所有數據
$attr = $m->select("p001,p002,p003");
$attr = $m->find("p001"); //找特定的數據根據主鍵值找

where可以加查詢條件
$attr = $m->where("code='p001' or sex=true")->select();

table可以切換要操作的表
$attr = $m->table("Nation")->select();

alias可以設置表的別名
$attr = $m->alias("人員")->select();

field可以指定查詢的字段
$attr = $m->field("code,name")->select();

order可以加排序條件
$attr = $m->order("Nation desc")->select();

group可以分組
$attr = $m->field("Nation")->group("Nation")->select();

having可以加分組后的條件
$attr = $m->field("Nation")->group("Nation")->having("count(*)>5")->select();

join可以連接多個表,在field里面要給字段加別名
$attr = $m->field("Info.Code as 代號,Info.Name as 姓名,Sex as 性別,Nation.Name as 民族名稱")->join("Nation on Info.Nation = Nation.Code")->select();

union聯合查詢
$attr = $m->field("name")->union("select name from nation")->select();

distinct去重
$attr = $m->field("Nation")->distinct(true)->select();

limit可以分頁,參數第一個代表跳過多少條,第二個代表取多少條
$attr = $m->limit(10,5)->select();

page可以分頁。第一個參數代表是當前頁,第二個參數代表每頁多少條
$attr = $m->page(3,5)->select();

取數據總條數
$attr = $m->count("*");
取某一列的和
$attr = $m->table("Car")->sum("Price");
取平均值
$attr = $m->table("Car")->avg("Price");
取最大值
$attr = $m->table("Car")->max("Price");
取最小值
$attr = $m->table("Car")->min("Price");


$sql = "select * from Info where Nation='n001'";
$attr = $m->query($sql);

$sql = "insert into Nation values('n104','按實際')";
$attr = $m->execute($sql);

$attr = $m->field("Info.Code as code,Info.Name as name,sex,Nation.Name as nationname,birthday")->join("Nation on Info.Nation = Nation.Code")->select();

$this->assign("info",$attr);

$this->assign("test",10);

$this->display();

    

ThinkPHP內置標簽

<table width="100%" border="1" cellpadding="0" cellspacing="0">
<tr>
<td>代號</td>
<td>姓名</td>
<td>性別</td>
<td>民族</td>
<td>生日</td>
</tr>
<foreach name="info" item="v" > //name是傳過來的名字,item是數組元素
<tr>
<td><{$v.code}></td>
<td><{$v.name}></td>
<td><{$v["sex"]?"男":"女"}></td>  //三目運算符不支持點操作
<td><{$v.nationname}></td>
<td><{$v.birthday}></td>
</tr>
</foreach>


</table>

<if condition="$test gt 10"> //condition是條件,因為是標簽為了防止歧義用備用詞
hello 5
<else />
hello 10
</if>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM