model层增删改查
新增
$user = new User;
$user->name = 'thinkphp';
$user->email = 'thinkphp@qq.com';
$user->save();
也可以使用data方法批量赋值:
$user = new User;
$user->data([
'name' => 'thinkphp',
'email' => 'thinkphp@qq.com']);
$user->save();
或者使用其他方法
$user = new User(['name'=>'thinkphp','email'=>'thinphp@qq.com']);
$user->save();
$user = new User();
$user->save(['name'=>'thinkphp','email'=>'thinphp@qq.com']);
$user = new User();
$user->insert(['name'=>'thinkphp','email'=>'thinphp@qq.com']);
如果需要过滤非数据表字段的数据,可以使用:
$user = new User($_POST);// 过滤post数组中的非数据表字段数据
$user->allowField(true)->save();
此方法不能与insert()方法进行使用
获取自增ID
$user = new User;
$user->name = 'thinkphp';
$user->email = 'thinkphp@qq.com';
$user->save();// 获取自增ID
echo $user->id;
添加多条数据
$user = new User;
$list = [
['name'=>'thinkphp','email'=>'thinkphp@qq.com'],
['name'=>'onethink','email'=>'onethink@qq.com']];
$user->saveAll($list);
saveAll方法新增数据默认会自动识别数据是需要新增还是更新操作,当数据中存在主键的时候会认为是更新操作;
查找并更新
$user = User::get(1);
$user->name = 'thinkphp';
$user->email = 'thinkphp@qq.com';
$user->save();
直接更新数据
$user = new User;// save方法第二个参数为更新条件
$user->save([
'name' => 'thinkphp',
'email' => 'thinkphp@qq.com']
,['id' => 1]);
静态方法
User::where('id', 1)
->update(['name' => 'thinkphp']);
或者使用:
User::update(['id' => 1, 'name' => 'thinkphp']);
删除模型数据,可以在实例化后调用delete方法。
$user = User::get(1);
$user->delete();
或者通过数据库类的查询条件删除
User::where('id','>',10)->delete();
查询
获取单个数据
取出主键为1的数据
$user = User::get(1);
echo $user->name;
或者在实例化模型后调用查询方法
$user = new User();// 查询单个数据
$user->where('name', 'thinkphp')
->find();
在实例化模型后调用查询方法
$user = new User();// 查询数据集
$user->where('name', 'thinkphp')
->limit(10)
->order('id', 'desc')
->select();
聚合
$user = new User;
$user->count();
$user->where('status','>',0)->count();
$user->where('status',1)->avg('score');
$user->max('score');