实例演示:查询构造器中的10个最常用的方法
Table(),field(),order(),where(),limit(),insert(),insertAll(),update(),delete(),以及如何获取自增主键和数据打包方法data()
<?php
namespace app\index\controller;
use think\Db;
class Query
{
//读操作返回的二维数组
//写操作返回的是受影响的记录数量
public function find()
{
//查询单条记录
$res = Db::table('users')->field(['name'=>'姓名'])->where('id','>',2)->find();
dump($res);
//查询多条记录
$res = Db::table('users')->order('id,desc')->limit(4)->select();
dump($res);
}
public function insert(){
//添加一条记录
$data = ['name'=>'thinkphp','password'=>234];
$num = Db::table('users')->insert($data);
return $num ? 'ok,id='.$id :'no';
//获取自增主键和数据打包方法data()
$data = ['name'=>'thinkphp','password'=>234];
$num = Db::table('users')->data($data)->insert();
$id = Db::getLastInsId();
return $num ? 'ok,id='.$id :'no';
//添加多条记录
$data = [ ['name'=>'thinkphp','password'=>234],
['name'=>'thinkphp1','password'=>1234],
];
$num = Db::table('users')->data($data)->insertAll();
return $num ? 'ok,num='.$num :'no';
}
public function update()
{
$num = Db::table('users')->where('id','=','2')->data(['age'=>Db::raw('age+1')])->update();
return $num ? 'ok,num='.$num :'no';
}
public function delete(){
$num = Db::table('users')->where('id','>',20)->delete();
return $num ? 'ok,num='.$num :'no';
}
}