手册目录
前言[随时更新]
MySQL快速复习
MySQL原生查询
选择数据表
删除数据
聚合查询
时间查询
视图查询
子查询
总结/参考
该方法看似简单,实际上功能非常强大,用户看到的最终结果,全部由这个方法进行控制,一定要重视

该方法返回值与其它连贯方法一样,返回查询对象自身;
参数:
| 序号 | 参数 | 说明 |
|---|---|---|
| 1 | $field字段列表 / mixed/(字符串、数组) | 表中存在的字段列表 |
| 2 | $except / 布尔 | 是否在结果中排除该字段,即不显示,默认为false,即不排除要显示 |
| 3 | $tableName / 字符串 | 通常不需要指定,由前面的table/name/db等方法或函数设置 |
| 4 | $prefix / 字符串 | 字段前缀,如果字段有前缀可设置,通常不设置 |
| 5 | $alias / 表的别名前缀 | 通常不需要设置,别名就够用了 |
<?php
namespace app\index\controller;
//导入数据库类
use think\Db;
class Index {
public function index(){
//查询表中id,name,salary字段,字段名用字符串
$result = Db::table('tp5_staff')
-> field('id,name,salary',false,'tp5_staff','','tp5_')
->select(1010);
//查看结果
dump($result);
}
}
代码中是完整的写法:
-> field('id,name,salary',false,'tp5_staff','','tp5_')
-> field('id,name,salary')
-> field(['id','name','salary'])
array(1) {
[0] => array(3) {
["id"] => int(1010)
["name"] => string(9) "欧阳峰"
["salary"] => float(4900)
}
}
<?php
namespace app\index\controller;
//导入数据库类
use think\Db;
class Index {
public function index(){
//查询表中id,name,salary字段,字段名用别名表示
//创建字段别名数组
$fields['id'] = '工号';
$fields['name'] = '姓名';
$fields['salary'] = '工资';
$result = Db::table('tp5_staff')
-> field($fields)
->select(1010);
//查看结果
dump($result);
}
}
$result = Db::table('tp5_staff')
-> field(['id'=>'工号','name'=>'姓名','salary'=>'工资'])
->select(1010);
$result = Db::table('tp5_staff')
-> field('id as 工号, name as 姓名, salary as 工资')
->select(1010);
array(1) {
[0] => array(3) {
["工号"] => int(1010)
["姓名"] => string(9) "欧阳峰"
["工资"] => float(4900)
}
}
以上二种(数组和字符串)设置字段别名的方式,显然数组方式更加灵活、优雅,便于扩展,也是我推荐使用的方式。
<?php
namespace app\index\controller;
//导入数据库类
use think\Db;
class Index {
public function index(){
//查询表中除id,sex字段外,其它字段均显示
$result = Db::table('tp5_staff')
-> field('id,sex',true) // 字段列表写在字符串中
->select(1010);
//查看结果
dump($result);
}
}
//查询表中除id,sex字段外,其它字段均显示
$result = Db::table('tp5_staff')
-> field(['id','sex'],true) // 字段列表写在数组中
->select(1010);
array(1) {
[0] => array(5) {
["name"] => string(9) "欧阳峰"
["age"] => int(28)
["salary"] => float(4900)
["dept"] => int(2)
["hiredate"] => string(10) "2013-09-22"
}
}
结果中,经过对比,并没有id,sex字段,可见也成功排除了这二个字段
思考:我们应该如何做呢?是把全部字段名列出来吗?
当然不是,如果那样做,也太LOW了~~~
经过总结,共有四种方式可以实现全部字段输出:
dump( Db::table('tp5_staff') -> select(1010) );
dump( Db::table('tp5_staff') ->field() -> select(1010) );
dump( Db::table('tp5_staff') ->field( '*' ) -> select(1010) );
dump( Db::table('tp5_staff') ->field( false ) -> select(1010) );
这四种方法,我个人推荐用 field('*') ,感觉显示更直观一些。
科技资讯
24小时阅读榜
1
2
3
4
5
6
7
8
9
10
精品课程
共5课时 | 18万人学习
共49课时 | 82.1万人学习
共29课时 | 65万人学习
共25课时 | 41.3万人学习
共43课时 | 76.7万人学习