# 数据查询
```
public function index()
{
// 查询数据一条
// get()方法传入查询的id
$res1 = User::get(1);
$res2 = User::get(function ($query){
$query->where('username','eq','000066')
->field('username, email');
});
// where方法
$res3 = User::where('id',43)->field('id, username')->find();
// 查询多条 查询的数据是一个对象
$res4 = User::all([22,29,54]);
foreach ($res4 as $val) {
//dump($val->toArray());
}
$res5 = User::all(function ($query){
$query->where("id", '<', 26)
->field('id, username, email');
});
foreach ($res5 as $val) {
//dump($val->toArray());
}
$res6 = User::where('id','<',26)->select();
foreach ($res6 as $val) {
//dump($val->toArray());
}
// 获取某个字段 value()
$res7 = User::where('id',22)->value('email');
//echo $res7;
// 获取某一列中的全部字段,第一个参数要获取的字段,第二个参数为数组的下表
$res8 = User::column("email","username");
dump($res8);
}
```
*****
# 添加数据
~~~
public function index()
{
// create()方法
$res = User::create([
'username' => 'admin',
'password' => md5(sha1('admin')),
'email' => 'admin@qq.com',
'num' => 100
],['username', 'email']); // 仅允许添加username和email字段
dump($res->id); // 获取添加数据的id
dump($res);
// save()方法需要先实例化模型
$userModel = new User();
$userModel->username = 'admin';
$userModel->email = 'admin@qq.com';
$userModel->save();
dump($userModel->id); // 获取添加数据的id
dump($userModel);
// save()方法的其他写法
$userModel = new User();
// allowField过滤掉不存在的字段如果为allowField(['username'])则只添加username字段
$res = $userModel->allowField(true)
->save([
'username' => 'admin',
'password' => md5('admin')
]);
dump($res->id); // 获取添加数据的id
dump($res);
}
~~~
*****
# 更新数据
~~~
// update方法适用于不需要验证的数据如果下面的代码执行2次看不出是否数据有改变
$res = User::update([
'id' => 1,
'username' => 'admin'
],function($query){
$query->where("id","LT",5) // id小于5
});
//$res = User::where('id',1)->update(['username'=>'admin']);
~~~