1、新增數據操做以下:php
1.第一種是實例化模型對象後賦值並保存:thinkphp
$user = new User; $user->name = 'thinkphp'; $user->email = 'thinkphp@qq.com'; $user->save();
2.第二種使用data
方法批量賦值:數組
$user = new User; $user->data([ 'name' => 'thinkphp', 'email' => 'thinkphp@qq.com' ]); $user->save();
3.直接在實例化的時候傳入數據函數
$user = new User([ 'name' => 'thinkphp', 'email' => 'thinkphp@qq.com' ]); $user->save();
4.過濾非數據表字段的數據post
$user = new User($_POST); // 過濾post數組中的非數據表字段數據 $user->allowField(true)->save();
5.經過外部提交賦值給模型,而且但願指定某些字段寫入spa
$user = new User($_POST); // post數組中只有name和email字段會寫入 $user->allowField(['name','email'])->save();
6.獲取自增IDcode
$user = new User; $user->name = 'thinkphp'; $user->email = 'thinkphp@qq.com'; $user->save(); // 獲取自增ID echo $user->id; //若是自增ID不是id而是u_id等,那麼獲取自增ID應該是u_id echo $user->u_id;
7.添加多條數據對象
$user = new User; $user->name = 'thinkphp'; $user->email = 'thinkphp@qq.com'; $user->save(); $user->name = 'onethink'; $user->email = 'onethink@qq.com'; // 第二次開始必須使用下面的方式新增 $user->isUpdate(false)->save();
8.支持批量新增,能夠使用blog
$user = new User; $list = [ ['name'=>'thinkphp','email'=>'thinkphp@qq.com'], ['name'=>'onethink','email'=>'onethink@qq.com'] ]; $user->saveAll($list);
9.saveAll
方法新增數據默認會自動識別數據是須要新增仍是更新操做,當數據中存在主鍵的時候會認爲是更新操做,若是你須要帶主鍵數據批量新增,那麼要以下設置參數class
$user = new User; $list = [ ['id'=>1, 'name'=>'thinkphp', 'email'=>'thinkphp@qq.com'], ['id'=>2, 'name'=>'onethink', 'email'=>'onethink@qq.com'], ]; $user->saveAll($list, false);
10.經過遍歷批量新增數據,能夠參考下面的方法:
$user = new User; $list = [ ['name'=>'thinkphp','email'=>'thinkphp@qq.com'], ['name'=>'onethink','email'=>'onethink@qq.com'] ]; foreach($list as $data){ $user->data($data,true)->isUpdate(false)->save(); }
11.靜態調用create
方法建立並寫入
$user = User::create([ 'name' => 'thinkphp', 'email' => 'thinkphp@qq.com' ]); echo $user->name; echo $user->email; echo $user->id; // 獲取自增ID
12.系統提供了model助手函數用於快速實例化模型,而且使用單例實現,例如:
// 使用model助手函數實例化User模型 $user = model('User'); // 模型對象賦值 $user->data([ 'name' => 'thinkphp', 'email' => 'thinkphp@qq.com' ]); $user->save();
13.進行批量新增
$user = model('User'); // 批量新增 $list = [ ['name'=>'thinkphp','email'=>'thinkphp@qq.com'], ['name'=>'onethink','email'=>'onethink@qq.com'] ]; $user->saveAll($list);