ThinkPHP模型(查询)

将convention.php中关于数据库的配置复制到 模块中的Conf/config.php文件中

TP框架中的模型用来操作数据库,写在model文件夹下, 数据库中的每张表对应到TP框架中就是一个类 表中的字段(列)对应为类的成员变量

如 使用Info表 就是一个Infomodel.class.php

如果不对表进行特殊操作 就可以不用去做Info的模型文件

1.原始方式

先做model模型

infoModel.class.php   表名+Model.class.php

<?php

namespace HomeModel;

use ThinkModel;
class infoModel extends Model
{
}

    调用方法输出

function DB()
{
$m=new HomeModelinfoModel();
var_dump($m);
}

2.使用快捷方法D() 相当于new
$m=D("info");

3.使用快捷方法M() 造父类model对象
$m=M("nation");
var_dump($m);

【操作数据库】
$attr=$m->select();//查询所有数据
$attr=$m->select("p001,p002"); //()内是一个参数,隔开 返回二维数组
$attr=$m->find("p001");//找特定一条数据,只能根据主键值找,返回一维数组

var_dump($attr);

【连贯操作】:类中的一个操作方法  执行完操作后 return一个$this  它还是一个对象  它还可以继续调用方法  直到某个不返回对象的方法

【数据查询方法支持的连贯操作方法有】:

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

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

alias 可以设置表的别名
$attr=$m->alias("haha")->select();
var_dump($m);

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

order 可以加排序条件默认升序 desc降序
$attr=$m->order("nation desc")->select();

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

having可以加分组后的条件
$attr=$m->field("nation")->group("nation")->having("count(*)>2")->select();
select nation from info group by nation having count(*)>2

join可以连接多个表,注意在field里要给字段加别名
$attr=$m->field("info.code,info.name as xingming,sex,nation.name")->join("nation on info.nation=nation.code")->select();//注意给查询的字段加别名

联合查询,一起显示
$attr=$m->field("name")->union("select name from nation")->select();

distinct去重 先查一列 再去重 需加参数true
$attr=$m->field("nation")->distinct(true)->select();

limit可以分页 参数 第一个代表跳过多少条 第二个代表取多少条(每页显示多少条)
$attr=$m->limit(3,3)->select();


page分页 第一个参数代表当前第几页,第二个参数代表每页多少条
$attr=$m->page(2,3)->select();

取数据总条数count 需写在最后
$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");

TP框架也支持原生sql语句 查询用query
$sql="select * from info where Nation='n001'";
$attr=$m->query($sql);

增删改用execute方法
$sql="insert into nation values('n009','神族')";
$attr=$m->execute($sql);
var_dump($attr);

【除了select find count聚合函数外 都是支持连贯操作的方法】

实例:在控制器的方法中查询好信息 然后在模板页面显示

$attr=$m->field("info.Code,info.Name,sex,nation.Name as nationname,birthday")->join("nation on info.Nation=nation.Code")->select();
$this->assign("info",$attr);
$this->display();

 <foreach>  注意:这里的<foreach>是标签                                     

</foreach>

<foreach name="info" item="v">
<tr>
<td><{$v.code}></td>        要小写
<td><{$v.name}></td>
<td><{$v["sex"]?"男":"女"}></td>    处理性别  TP框架支持三元运算符  使用三元运算符时,不支持 . 语法
<td><{$v.nationname}></td>   处理民族  在查询的时候使用join
<td><{$v.birthday}></td>
</tr>
</foreach>

<if></if>

<if condition="$test gt 10">  判断是不能出现>或<  要有gt lt 代替
yes
<else />
no
</if>

原文地址:https://www.cnblogs.com/hamilton/p/5723109.html