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值:

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

更新

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

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

更新 JSON 字段

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

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

自增与自减

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

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

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 语法:

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();

 

posted on 2018-10-19 14:33  小V_chen  阅读(203)  评论(0编辑  收藏  举报

导航