tp5.0 模型查询数据的返回类型,分页

一开始用painate()这个函数的时候,发现有的查询方式不能使用这个函数,由此了解到了模型查询和普通查询返回类型的不同

1.原生查询方法

Db::query("select * from shop");

查询成功返回:二维数组


array(2) {
  [0]=>
  array(5) {
    ["username"]=>
    string(0) ""
    ["title"]=>
    string(10) "java课本"
    ["comment"]=>
    string(22) "java课本课本课本"
    ["time"]=>
    string(19) "2019-02-18 23:12:03"
    ["id"]=>
    int(1)
  }
  [1]=>
  array(5) {
    ["username"]=>
    string(0) ""
    ["title"]=>
    string(1) "c"
    ["comment"]=>
    string(10) "cccccccccc"
    ["time"]=>
    string(19) "2019-02-18 23:12:26"
    ["id"]=>
    int(2)
  }
}


查询失败:array(0) { }

二维数组为空  

2.查询构造器

select方法

Db::table('shop')->select(); 

返回的是二维数组,和原生的查询结果一样,查询失败同样返回空数组。

find方法

Db::table('shop')->find();  

只能查询一条数据,返回的是第一个查询到的数据,方式是一维数组

array(5) {
  ["username"] => string(0) ""
  ["title"] => string(10) "java课本"
  ["comment"] => string(22) "java课本课本课本"
  ["time"] => string(19) "2019-02-18 23:12:03"
  ["id"] => int(1)
}

查询失败:NULL

需要分页的时候:

Db::name('shop')->paginate(10);
需要分页的时候不能用select,因为数组在tp5中是不支持直接分页的,->paginate()的使用者必须是个object类型。

3.模型

首先知道,模型查出来的数据都是对象,要转化为数组的方法是在database.php加上

'resultset_type' => '	hinkCollection',
便可以调用->toArray()方法  

实际上,因为tp5框架的设计,两种数据在进行数据处理上没有差别

1.get方法

①用来查询一条数据

$test3=Shop::get(1);或者$test3 = Shop::get(['id' => '1']);
echo $test3->time;

返回类型:对象。

通过

$test3=Shop::get(1)->toArray();变为一维数组

②查询失败:返回NULL

2.all方法

① 用来查询一堆数据,toArray()后变为二维数组
② 遍历


foreach ($test3 as $key => $value) {
    		var_dump($value['time']);//time是字段名字
    	}

③查询失败

不变为数组返回:} object(thinkCollection)#19 (1) { ["items":protected]=> array(0) { } }

变为数组返回:空数组

3.select方法

$test4=Shop::select();
    	foreach ($test4 as $key ) {
    		var_dump($key['time']);//time字段
    	}
    	
使用处理二维数组的方法处理就好了

4.find也可以用

5.分页

使用者必须是对象

模型的分页,官方:
$test6=Shop::paginate(10);

我自己试了下,发现find查询出来的语句也是可以分页的,select就不行了。

原文地址:https://www.cnblogs.com/zaqzzz/p/10400894.html