讲师中心 微信公众号
AI工具推荐 视频效率加速

ThinkPHP5数据库实例详解

浏览21089
更新时间2022-01-20

Query对象查询

1、功能:直接用Query对象查询

通过前面的学习,大家都知道了各种查询方法,都是间接通过调用Query类的相应方法来实现的,因为也完全可以直接使用Query类实例来完成查询。

2、源码:/thinkphp/library/think/db/Query.php

······
//注释部分是我加上的,源码中是没有的
public function select($data = null)
    {
        if ($data instanceof Query) { //如果$data是Query类的实例
            return $data->select();    //直接调用select方法获取结果集并返回
        }        
······

如何select参数是Query类实例,就直接调用该对象的select方法返回数据集。同理,如果前面有连贯操作一律无效,以Query对象调用的方法为主进行查询。

3、实例演示:

任务1:查询tp5_staff表中工资大于8000的前3个员工信息

  • Index.php 控制器代码:
<?php
namespace app\index\controller;
//导入数据库类
use think\Db;

class Index {
  public function index(){  

  //1.创建Query对象
  $query = new \think\db\Query();

  //2.创建Query查询对象
  $query -> table('tp5_staff')
         -> field('id,name,salary')
         -> where('salary','>',8000)
         -> order('id desc')
         -> limit(3);

  //3.执行查询(select方法前不要有其它连贯方法,即使有也无效)
  $result = Db::select($query);

  //4.输出结果
  dump($result);
  }
}
  • 查询结果:
array(3) {
  [0] => array(3) {
    ["id"] => int(1028)
    ["name"] => string(6) "方方"
    ["salary"] => float(9877)
  }
  [1] => array(3) {
    ["id"] => int(1023)
    ["name"] => string(9) "段王爷"
    ["salary"] => float(9560)
  }
  [2] => array(3) {
    ["id"] => int(1011)
    ["name"] => string(9) "李云龙"
    ["salary"] => float(9850)
  }
}
  • 生成的SQL语句:
SELECT `id`,`name`,`salary` FROM `tp5_staff` WHERE `salary` > 8000 ORDER BY id desc LIMIT 3

4、总结:

Query对象查询方式,实际开发中用得不多,但提供给我们另一种选择

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn