laravel 数据库操做

插入数据库

查询构造器还提供了 insert 方法用于插入记录到数据库中。 insert 方法接收数组形式的字段名和字段值进行插入操做:数组

DB::table('users')->insert(
    ['email' => 'john@example.com', 'votes' => 0]
);

你还能够在 insert 中传入一个嵌套数组向表中插入多条记录。每一个数组表明要插入表中的行:函数

DB::table('users')->insert([
    ['email' => 'taylor@example.com', 'votes' => 0],
    ['email' => 'dayle@example.com', 'votes' => 0]
]);

自增 ID

若是数据表有自增ID,使用 insertGetId 方法来插入记录并返回ID值:spa

$id = DB::table('users')->insertGetId(
    ['email' => 'john@example.com', 'votes' => 0]
);

更新

固然,除了插入记录到数据库中,查询构造器也可经过 update 方法更新已有的记录。 update 方法和 insert 方法同样,接受包含要更新的字段及值的数组。 你能够经过 where 子句对 update 查询进行约束: code

DB::table('users')
            ->where('id', 1)
            ->update(['votes' => 1]);

更新 JSON 字段

更新 JSON 字段时,你能够使用 -> 语法访问 JSON 对象上相应的值,该操做只能用于支持 JSON 字段类型的数据库:对象

DB::table('users')
            ->where('id', 1)
            ->update(['options->enabled' => true]);

自增与自减

查询构造器还为给定字段的递增或递减提供了方便的方法。 此方法提供了一个比手动编写 update 语句更具表达力且更精练的接口。blog

这两个方法都至少接收一个参数:须要修改的列。第二个参数是可选的,用于控制列递增或递减的量接口

DB::table('users')->increment('votes');

DB::table('users')->increment('votes', 5);

DB::table('users')->decrement('votes');

DB::table('users')->decrement('votes', 5);

你也能够在操做过程当中指定要更新的字段:事务

DB::table('users')->increment('votes', 1, ['name' => 'John']);

Deletes

查询构造器也能够使用 delete 方法从数据表中删除记录。在使用 delete 前,可添加 where 子句来约束 delete 语法:rem

DB::table('users')->delete();

DB::table('users')->where('votes', '>', 100)->delete();

若是你须要清空表,你能够使用 truncate 方法,这将删除全部行,并重置自增 ID 为零:

DB::table('users')->truncate();

 

悲观锁

查询构造器也包含一些能够帮助你在 select 语法上实现 「悲观锁定」的函数。若想在查询中实现一个「共享锁」,你能够使用 sharedLock 方法。共享锁可防止选中的数据列被篡改,直到事务被提交为止 :

DB::table('users')->where('votes', '>', 100)->sharedLock()->get();

另外,你也能够使用 lockForUpdate 方法。使用「更新」锁可避免行被其它共享锁修改或选取:

DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();
相关文章
相关标签/搜索