数据插入、更新、删除


更新

方法

  1. $ret = User::where('id', 100)->update([
  2. 'nickname' => 'tomener',
  3. 'updated' => NOW_TIME
  4. ]);

返回值

  1. 成功:返回影响函数,影响行数有可能为0
  2. 失败:返回false
  3. 判断返回值不全等于false就表示更新成功$ret !== false

加减

  1. Course::where(87)->update([
  2. 'view_num' => ['+', 2]
  3. ]);
  1. SQL: UPDATE course SET view_num = view_num + 2 WHERE id = 87

自增、自减

  1. //SQL: UPDATE archive SET view_num = view_num + 1 WHERE id = 100
  2. Archive::where(100)->inc('view_num');
  3. //SQL: UPDATE archive SET view_num = view_num + 10 WHERE id = 100
  4. Archive::where(100)->inc('view_num', 10);
  5. //SQL: UPDATE archive SET view_num = view_num - 1 WHERE id = 100
  6. Archive::where(100)->dec('view_num');
  7. //SQL: UPDATE archive SET view_num = view_num - 10 WHERE id = 100
  8. Archive::where(100)->dec('view_num', 10);

插入数据

方法

  1. use model/user/User;
  2. User::insert([
  3. 'nickname' => 'Tommy',
  4. 'avatar' => '983602894.jpg',
  5. 'sex' => 1
  6. ]);
  1. 插入当前模型对应的表

返回值

成功:返回插入的自增主键ID的值,如果表主键不是自增的,那么,返回插入的主键的值

失败:返回false

批量插入

  1. use model/user/User;
  2. User::insertMulti([
  3. ['nickname' => 'Tommy', 'avatar' => '983602894.jpg', 'sex' => 1],
  4. ['nickname' => 'Jully', 'avatar' => '689485838.jpg', 'sex' => 0],
  5. ['nickname' => 'luccy', 'avatar' => '548925657.jpg', 'sex' => 0],
  6. ]);

删除数据

删除id=5178的用户

  1. use model\user\User as UserModel;
  2. use Timo\Core\App;
  3. use Timo\Core\Request;
  4. class User
  5. {
  6. public function del()
  7. {
  8. $uid = Request::postInt('uid'); //uid = 5178
  9. $ret = UserModel::where('id', $uid)->delete();
  10. if (!$ret) {
  11. return App::result(1, '删除失败');
  12. }
  13. return App::result(0, '删除成功');
  14. }
  15. }

我们不推荐物理删除,一般,我们会有一个status字段,-1表示删除,0表示隐藏,1表示显示。