摘要:<?php namespace app\index\controller; use think\DB; use app\index\model\User; class Index { public function index() {
<?php
namespace app\index\controller;
use think\DB;
use app\index\model\User;
class Index
{
public function index()
{
return view();
}
public function find()
{
// $res = User::find(); //用sql语句进行查询
// $res = User::where('user_id','>',6)->find(); //用模型进行查询一条数据,返回最近的一条
$res = User::where(function($query){
$query->where('user_id','>',6);
})->find(); //用闭包函数进行查询条件创建
dump($res);
}
public function select()
{
// $res = User::select();
$res = User::select(function($query){
$query->where('sallary','>',5000);
});
dump($res);
}
public function update()
{
// $res = User::update(
// ['sallary'=> DB::raw('sallary+1000')],
// ['user_id'=>1]
// );
$res = User::update(
['sallary'=> DB::raw('sallary+1000')],
function($q){
$q->where('sallary','<','4000');
}
);
dump($res);
}
public function delete(){
// $res = User::destroy(1);//软删除成功
// $res = User::where('user_id','<',3)->select(); //获取数据,不包括软删除的数据
// $res = User::withTrashed()->where('user_id','<',3)->select(); //查询所有数据,包括软删除的数据
$res = User::onlyTrashed()->where('user_id','<',3)->select();//只获取软删除的数据
dump($res);
}
public function insert()
{
//$res = DB::query('select * from user');
// $data = ['user_name'=>'PHP','sex'=>1,'age'=>19,'sallary'=>8000];
// $res = DB::table('user')->insert($data); //插入一条数据,返回影响的条数
$data = ['user_name'=>'bootstrap','sex'=>1,'age'=>52,'sallary'=>4300];
// $res = DB::table('user')->insertGetId($data);//插入一条数据,并返回插入的ID
// $userModel = new User();
// $res = $userModel->save($data); //返回是个布尔型值
$res = User::create($data); //静态方法进行添加操作,返回是个对象类型
var_dump($res->user_id);die;
}
public function hello($name = 'ThinkPHP5',$sex='18')
{
return 'hello,' . $name.'年龄:'.$sex;
}
}模型代码如下:
<?php
namespace app\index\model;
use think\Model;
use think\model\concern\SoftDelete;
class User extends Model
{
use SoftDelete;
protected $table = 'user'; //定义数据表
protected $pk = 'user_id'; //定义主键,默认为id
protected $deleteTime = 'delete_time'; //设置软删除的字段
protected $defaultSoftDelete = 0; //设置软删除默认字段值
}总结:
闭包函数:就是 把函数相当于一个参数传递过去。
模型:模型可以设置很多条件,例如软删除,比原生sql语句使用起来方便。问:但是不知道速度差距明显吗,数据少显示不出来,数据多了呢?
批改老师:查无此人批改时间:2019-03-16 10:46:14
老师总结:数据库查询的速度,在于你的条件。你的条件明确,对查询速度不影响。继续加油