添加

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

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

批量添加

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

自增 IDs

如果数据表有自增 ID ,使用 insertGetId 方法来插入记录可以返回 ID 值:

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

更新

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

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

更新或新增

有时您可能希望更新数据库中的现有记录,或者如果不存在匹配记录则创建它。 在这种情况下,可以使用 updateOrInsert 方法。 updateOrInsert 方法接受两个参数:一个用于查找记录的条件数组,以及一个包含要更改记录的键值对数组。

updateOrInsert 方法将首先尝试使用第一个参数的键和值对来查找匹配的数据库记录。
如果记录存在,则使用第二个参数中的值去更新记录。
如果找不到记录,将插入一个新记录,新增的数据是两个数组的集合:

DB::table('users')
    ->updateOrInsert(
        [ 'name' => '大郎'],
        ['age' => 80]
    );

删除

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

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

DB::table('users')->where('age', '>', 18)->delete();

您可以使用 truncate 方法来清空整个表,这将移除所有的数据并重置所有的自增 ID 为 0 :

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