namespace app\index\controller;
use think\Db;
class Query
{
public function select()
{
$res = Db::table('staff')
// ->field('staff_id','name','salary')
->find(14);
dump($res);
}
public function selectAll()
{
$res = Db::table('staff')
->field(['staff_id'=>'编号','name'=>'姓名','salary'=>'工资']) //设置字段别名
->where('salary','>',6000)
->order('salary','DESC')
->limit(3)
->select();
dump($res);
}
public function insert1()
{
$data = [
'name'=>'葛优',
'sex'=>1,
'age'=>57,
'salary'=>13000
];
$res = Db::table('staff')
->data($data)
->insert();
$id = Db::getLastInsID();
dump($id);
}
public function insert2()
{
$data = [
'name' => '韦小宝',
'sex' => 0,
'age' => 23,
'salary' => 7865
];
$id = Db::table('staff')
->insertGetId($data);
dump($id);
}
public function insertAll()
{
$data = [
['name' => '韩愈','sex' => 0,'age' => 56,'salary' => 15000],
['name' => '柳宗元','sex'=> 0,'age' => 48,'salary' => 14000],
['name' => '西施','sex'=> 1,'age' => 21,'salary' => 19000],
['name' => '杨贵妃','sex' => 1,'age' => 26,'salary' => 25000]
];
$num = Db::table('staff')->data($data)->insertAll();
return $num ? '成功插入'.$num.'条记录' : '插入记录失败';
}
public function update1()
{
$res = Db::table('staff')
->where('salary','>=',8000)
->data(['salary' =>Db::raw('salary-500')]) //要引用原字段的值,要用Db::raw()引用原始数据
->update();
return $res ? '更新记录数为:'.$res : '更新记录失败!';
}
public function update2()
{
$res = Db::table('staff')
->data(['salary' => Db::raw('salary+450')])
->update(['staff_id' => 9]);
return $res ? '更新记录数为:'.$res : '更新记录失败!';
}
}