前言[随时更新]
MySQL快速复习
MySQL原生查询
选择数据表
删除数据
聚合查询
时间查询
视图查询
子查询
总结/参考
/**
* 指定当前操作的数据表
* @access public
* @param mixed $table 表名
* @return $this
*/
public function table($table)
{
if (is_string($table)) {
if (strpos($table, ',')) {
$tables = explode(',', $table);
$table = [];
foreach ($tables as $item) {
list($item, $alias) = explode(' ', trim($item));
if ($alias) {
$this->alias([$item => $alias]);
$table[$item] = $alias;
} else {
$table[] = $item;
}
}
} elseif (strpos($table, ' ')) {
list($table, $alias) = explode(' ', $table);
$table = [$table => $alias];
$this->alias($table);
}
} else {
$tables = $table;
$table = [];
foreach ($tables as $key => $val) {
if (is_numeric($key)) {
$table[] = $val;
} else {
$this->alias([$key => $val]);
$table[$key] = $val;
}
}
}
$this->options['table'] = $table;
return $this;
}
重要提示:setTable方法功能与table非常类似,但还是有区别的:
1、table方法指定当前正在操作的数据表;
2、setTable方法设置当前脚本默认的数据表;
3、即当前脚本中,如果用setTable设置了默认数据表,那么后面语句就不用再次调用table了。
//设置了默认数据表为:setTable( 'tp5_staff' ),后面的操作都针对该表 dump( Db::setTable( 'tp5_staff' ) -> where( 'id = 1020' ) -> find( ) ) ; //查询 id= 1025的记录,不用再设置数据表了 dump( Db:: where( 'id = 1020' ) -> find( ) ) ;
为了代码清晰,健壮易扩展,不建议用setTable来牺牲灵活性
dump( )方法介绍:
1.dump( )方法是框架提供给开发者的一个非常好用的调式工具,可以对运行结果中的数据进行人性化的展示,可以认为是PHP原生var_dump( )函数加强版,或者格式化的var_dump( );
2.dump( ) 方法,定义在:/thinkphp/library/think/Debug.php 类中,该类随框架启动,所以你可以直接使用dump( )
3.如果你这样使用:Debug::dump( ) 也可以,但必须在脚本前面引入Debug.php类文件 ,即:use think\Debug;
dump(Db::table('tp5_staff')->find('1003'));
dump(Db::table('tp5.tp5_staff')->find('1003'));
dump(Db::table(['tp5.tp5_staff'=>'staff'])->find('1003'));
array(7) {
["id"] => int(1003)
["name"] => string(6) "杨过"
["sex"] => int(0)
["age"] => int(35)
["salary"] => float(5303)
["dept"] => string(9) "市场部"
["hiredate"] => string(10) "2014-09-22"
}