🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# **添加一条数据** ## **save()** >[danger]成功返回true ~~~ $user = new User; $user->name = 'thinkphp'; $user->email = 'thinkphp@qq.com'; $user->save(); // 获取自增ID echo $user->id; ~~~ 或者: ~~~ $user->save([ 'name' => 'thinkphp', 'email' => 'thinkphp@qq.com' ]); // 获取自增ID echo $user->id; ~~~ 或者: ~~~ $user->allowField(['name','email'])->save($_POST); // 获取自增ID echo $user->id; ~~~ 或者(推荐): ~~~ // 过滤post数组中的非数据表字段数据 $data = \think\facade\Request::only(['name','email']); $user->save($data); // 获取自增ID echo $user->id; ~~~ `save`方法可以支持`replace`写入。 ~~~ $user = new User; $user->name = 'thinkphp'; $user->email = 'thinkphp@qq.com'; $user->replace()->save(); ~~~ ## **::create()** >[danger]返回的是当前模型的对象实例 >默认会过滤掉不是数据表的字段信息 >第二个参数也可指定数据表中允许写入的字段(想要那个字段就填到此处) ~~~ $user = User::create([ 'name' => 'thinkphp', 'email' => 'thinkphp@qq.com' ]); echo $user->name; echo $user->email; echo $user->id; // 获取自增ID ~~~ `create`方法默认会过滤不是数据表的字段信息,可以在第二个参数可以传入允许写入的字段列表,例如: ~~~ // 只允许写入name和email字段的数据 $user = User::create([ 'name' => 'thinkphp', 'email' => 'thinkphp@qq.com' ], ['name', 'email']); echo $user->name; echo $user->email; echo $user->id; // 获取自增ID ~~~ 支持`replace`操作,使用下面的方法: ~~~ $user = User::create([ 'name' => 'thinkphp', 'email' => 'thinkphp@qq.com' ], ['name','email'], true); ~~~ # **批量增加数据** ## **saveAll** >[info]saveAll方法新增数据返回的是包含新增模型(带自增ID)的数据集Collection对象。 如果有某条新增失败会报错并回滚 ~~~ $user = new User; $list = [ ['name'=>'thinkphp','email'=>'thinkphp@qq.com'], ['name'=>'onethink','email'=>'onethink@qq.com'] ]; $user->saveAll($list); ~~~