插入(Insert)
查询构建器还提供了insert方法来插入记录到数据表。insert方法接收数组形式的列名和值进行插入操作:
DB::table('users')->insert(
['email' => 'john@example.com', 'votes' => 0]);
你甚至可以一次性通过传入多个数组来插入多条记录,每个数组代表要插入数据表的记录:
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]
);
注意:当使用PostgresSQL时insertGetId方法默认自增列被命名为id,如果你想要从其他”序列“获取ID,可以将序列名作为第二个参数传递到insertGetId方法 www.anxinzl.top。
更新(Update)
当然,除了插入记录到数据库,查询构建器还可以通过使用update方法更新已有记录。update方法和insert方法一样,接收列和值的键值对数组包含要更新的列,你可以通过where子句来对update查询进行约束:
DB::table('users')
->where('id', 1)
->update(['votes' => 1]);
增加/减少
查询构建器还提供了方便增减给定列名数值的方法。相较于编写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']);
删除(Delete)
当然,查询构建器还可以通过delete方法从表中删除记录:
DB::table('users')->delete();
在调用delete方法之前可以通过添加where子句对delete语句进行约束:
DB::table('users')->where('votes', '<', 100)->delete();