数据插入、更新、删除
更新
方法
$ret = User::where('id', 100)->update([
'nickname' => 'tomener',
'updated' => NOW_TIME
]);
返回值
成功:返回影响函数,影响行数有可能为0
失败:返回false
判断返回值不全等于false就表示更新成功$ret !== false
加减
Course::where(87)->update([
'view_num' => ['+', 2]
]);
SQL: UPDATE course SET view_num = view_num + 2 WHERE id = 87
自增、自减
//SQL: UPDATE archive SET view_num = view_num + 1 WHERE id = 100
Archive::where(100)->inc('view_num');
//SQL: UPDATE archive SET view_num = view_num + 10 WHERE id = 100
Archive::where(100)->inc('view_num', 10);
//SQL: UPDATE archive SET view_num = view_num - 1 WHERE id = 100
Archive::where(100)->dec('view_num');
//SQL: UPDATE archive SET view_num = view_num - 10 WHERE id = 100
Archive::where(100)->dec('view_num', 10);
插入数据
方法
use model/user/User;
User::insert([
'nickname' => 'Tommy',
'avatar' => '983602894.jpg',
'sex' => 1
]);
插入当前模型对应的表
返回值
成功:返回插入的自增主键ID的值,如果表主键不是自增的,那么,返回插入的主键的值
失败:返回false
批量插入
use model/user/User;
User::insertMulti([
['nickname' => 'Tommy', 'avatar' => '983602894.jpg', 'sex' => 1],
['nickname' => 'Jully', 'avatar' => '689485838.jpg', 'sex' => 0],
['nickname' => 'luccy', 'avatar' => '548925657.jpg', 'sex' => 0],
]);
删除数据
删除id=5178的用户
use model\user\User as UserModel;
use Timo\Core\App;
use Timo\Core\Request;
class User
{
public function del()
{
$uid = Request::postInt('uid'); //uid = 5178
$ret = UserModel::where('id', $uid)->delete();
if (!$ret) {
return App::result(1, '删除失败');
}
return App::result(0, '删除成功');
}
}
我们不推荐物理删除,一般,我们会有一个status字段,-1表示删除,0表示隐藏,1表示显示。