Think PHP5.0模型操作之查询数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_41665015/article/details/80099468

获取单个数据

方法:

1)通过模型调用get方法,在里面传入对应的主键。

//取出主键为一的数据

$user = UserModel(1);

echo $user->name;

2)通过数组

//使用数组查询、

$user = UserModel::get(['name','thinkphp' ]); //寻找name为蒋欣这一条记录

echo $user->email;

或者在实例化模型后调用查询

$user = new UserModel();

//查询单个数据

$result = $user->where('name' => 'thinkphp' )->find();

echo $result->name;

get或者find方法返回的是当前模型的对象实例,可以使用模型的方法


获取多个数据

取出多个数据

//根据主键获取多个数据(使用all方法)

$list = UserModel::all('1,2,3');

//或者里面的条件采用数组的方式

$list = UserModel::all('1,2,3');

foreach($list as $value => $key)

{  

        echo $value -> name;

}

//使用数组查询

$list = UserModel::all(['stadus' => 1]);

或者在实例化模型后调用查询方法

$user = new  UserModel();

//查询数据集

$result -> where('stadus' ,1) ->limt(2) ->order('id' ,'desc') -> select();

foreach($result as $value => $key)

{  

        echo $value [' name '];

}


模型的all方法或者select 方法返回的是一个包含模型对象的二维数组或者数据集对象。

聚合

在应用中我们经常会用到一些统计数据,例如当前所有(或者满足某些条件)的用户数、所有用户的最大积分、用户的平均成绩等等,ThinkPHP为这些统计操作提供了一系列的内置方法,包括:

方法 说明
count 统计数量,参数是要统计的字段名(可选)
max 获取最大值,参数是要统计的字段名(必须)
min 获取最小值,参数是要统计的字段名(必须)
avg 获取平均值,参数是要统计的字段名(必须)
sum 获取总分,参数是要统计的字段名(必须)

子(可以查询手册)

获取用户数:

 
 
  1. Db::table('think_user')->count();
  2. // 助手函数
  3. db('user')->count();

或者根据字段统计:

 
 
  1. Db::table('think_user')->count('id');
  2. // 助手函数
  3. db('user')->count('id');

静态调用

UserModel:: count();

UserModel::where( ' status ' ,' > ' ,0) -> count();

UserModel::where( ' status ' , 1) ->avg( ' score ' );

UserModel::max( ' score ' );

动态调用;

$user = UserModel ;

$user ->count();

$user ->where( ' status ' ,' > ' ,0) -> count();

$user ->where( ' status ' , 1) ->avg( ' score ' );

时间:2018.4.26

猜你喜欢

转载自blog.csdn.net/qq_41665015/article/details/80099468