单数据新增
- 使用insert()方法可以向数据表中添加一条数据
- 如果新增成功,会返回一个1
- 如果添加一个不存在的字段数据,会抛出一个异常Exception
$data = [
'username' => 'zhh',
'pass' => 123,
'gender' => '女',
'email' => 'zhh@qq.com',
'price' => '70',
'create_time' => time(),
'update_time' => time()
];
return Db::name('user')->insert($data);
- 如果想强行新增并且抛弃不存在的字段数据,则使用strick(false)方法,忽略异常
$data = [
'username' => 'zhh',
'pass' => 123,
'gender' => '女',
'email' => 'zhh@qq.com',
'price' => '70',
'create_time' => time(),
'update_time' => time(),
'abc' => 123
];
return Db::name('user')->strict(false)->insert($data);
- 如果使用的数据库是mysql数据库,支持replace写入
- insert和replace写入的区别,前者表示表中存在主键相同则报错,后者则修改
$data = [
'username' => 'zhh',
'pass' => 123,
'gender' => '女',
'email' => 'zhh@qq.com',
'price' => '70',
'create_time' => time(),
'update_time' => time(),
];
Db::name('user')->replace()->insert($data);
- 使用insertGetId()方法,可以在新增成功后返回当前数据ID
$data = [
'username' => 'zhh',
'pass' => 123,
'gender' => '女',
'email' => 'zhh@qq.com',
'price' => '70',
'create_time' => time(),
'update_time' => time(),
];
return Db::name('user')->insertGetId($data);
批量数据新增
$data = [
[
'username' => 'tl',
'pass' => 123,
'gender' => '女',
'email' => 'tl@qq.com',
'price' => '70',
'create_time' => time(),
'update_time' => time(),
],
[
'username' => '曾庆兴',
'pass' => 123,
'gender' => '女',
'email' => 'zqx@qq.com',
'price' => '70',
'create_time' => time(),
'update_time' => time(),
]
];
return Db::name('user')->insertAll($data);
- 批量新增也支持relace()方法,添加后改变成replace into
save()新增
- save()方法是一个通用方法,可以自行判断是否新增还是修改数据
- save()方法判断是否为新增或修改的依据为:是否存在主键,不存在则新增
$data = [
'username' => 'zhh',
'pass' => 123,
'gender' => '女',
'email' => 'zhh@qq.com',
'price' => '70',
'create_time' => time(),
'update_time' => time(),
];
return Db::name('user')->save($data);