Laravel5.1 框架数据库查询构建器用法实例详解(4)
当你需要拿到插入数据的ID的话,可以使用获取自增ID的方法:
public function getInsertArticle()
{
// 插入一条数据:
$id = DB::table('articles')->insertGetId(
['title'=>'get more', 'body'=>'emmmmmm......']
);
dd($id);
}
4 更新
public function getUpdateArticle()
{
$result = DB::table('articles')->whereBetween('id', [1, 3])->update(['comment_count'=>0]);
dd($result);
}
↑ update还可以返回影响了几条数据。
4.1 加/减快捷方法
public function getUpdateArticle()
{
$result = DB::table('articles')->whereBetween('id', [1, 3])->increment('comment_count',2);
dd($result);
}
↑ increment接受1~2个参数,第一个参数是列名,第二个参数是可选的表示增加几(默认是1),上面的语句是:comment_count这一列的值增加2。
public function getUpdateArticle()
{
$result = DB::table('articles')->whereBetween('id', [1, 3])->decrement('comment_count',2);
dd($result);
}
↑ decrement接受1~2个参数,第一个参数是列名,第二个参数是可选的表示减少几(默认是1),上面的语句是:comment_count这一列的值减少2。
你以为加减快捷方法只接收两个参数么?nonono 它还可以接收第三个参数:
public function getUpdateArticle()
{
$result = DB::table('articles')->whereBetween('id', [1, 3])->increment('comment_count', 2, ['title' => 'testUpdate']);
dd($result);
}
↑ 它还可以在增加/减少时对其他列进行修改。
5 删除
public function getDeleteArticle()
{
$result = DB::table('articles')->whereBetween('id', [1, 3])->delete();
dd($result);
}
↑ 用delete删除数据,它也返回有多少行被影响。
当你想要删除所有的列 并且把自增ID归0的话 可以这么做:
public function getDeleteArticle()
{
DB::table('articles')->truncate();
}
6 锁
查询构建器还包含一些方法帮助你在select语句中实现”悲观锁“。可以在查询中使用sharedLock方法从而在运行语句时带一把”共享锁“。共享锁可以避免被选择的行被修改直到事务提交:
DB::table('articles')->where('id', '>', 100)->sharedLock()->get();
此外你还可以使用lockForUpdate方法。”for update“锁避免选择行被其它共享锁修改或删除:
DB::table('articles')->where('id', '>', 100)->lockForUpdate()->get();
内容版权声明:除非注明,否则皆为本站原创文章。
